Thursday, 29 September 2011

SQL Server PIVOT

Example using the PIVOT command to construct a crosstab.
-- table definition CREATE TABLE [dbo].[server] ( [server_id] [int] IDENTITY(1,1) NOT NULL, [server_name] [varchar](30) NULL, [product] [varchar](30) NULL, [data_centre] [varchar](100) NULL, [business_unit] [varchar](100) NULL, CONSTRAINT [pk_server] PRIMARY KEY NONCLUSTERED ( [server_id] ASC) ) -- use pivot to display the number of servers by product for each business unit and data centre. DECLARE @products varchar(max) ,@sql varchar(max) SELECT @products = STUFF(( SELECT DISTINCT '],[' + product FROM dbo.[server] ORDER BY '],[' + product FOR XML PATH('') ), 1, 2, '') + ']' SET @sql = ' SELECT * FROM ( SELECT product, business_unit, data_centre FROM dbo.[server] ) t PIVOT (count(product) FOR product IN(' + @products + ')) as pvt ' EXEC (@sql)

Sample Results

business_unitdata_centreIMAGEMySQLNASSNAPSOLRSQL SERVER
UnitADatacentre10100065
UnitBDatacentre1131009
UnitADatacentre2070136
UnitBDatacentre2110012
UnitADatacentre3020002
UnitBDatacentre3010004

Wednesday, 7 September 2011

Database Mirror Recovery

If the primary database is still accessible then switch over to the secondary can be achieved by running the following code on the primary server for each of the failed databases.
ALTER DATABASE db_name SET PARTNER FAILOVER

If the primary database is not accessible then the secondary database can be forced on-line by removing the mirror and running the restore command for each of the failed databases.

ALTER DATABASE db_name SET PARTNER OFF RESTORE DATABASE db_name WITH RECOVERY