Tuesday, 12 May 2015

Pivot table


 

DECLARE @columns VARCHAR(1000)    

SELECT @columns = COALESCE(@columns + ',[' + cast(Status as varchar) + ']','[' + cast(Status as varchar)+ ']')       
FROM(           
  Select Status From Statuses          
) x     
     
print @columns

DECLARE @query nVARCHAR(4000)     

SET @query = ';with CTE_Result as
(
      select Applications.AppName,Computers.Status
      from Applications
      left join Installations on Installations.AppID = Applications.AppID
      left join Computers on Computers.HostID = Installations.HostID
      WHere AppName=''Adobe AIR''
      --group by Applications.AppName,Computers.Status
)
SELECT * FROM
(
      SELECT * from CTE_Result
) as S PIVOT
( COUNT(Status) FOR [Status] IN ('+ @columns + ')) AS PivotTable'
 print @columns    
EXECUTE(@query)    


Result is 

 

Friday, 1 May 2015

Try catch block in store procedure


CREATE PROCEDURE demoTryCatchTest
AS
BEGIN TRY
    SELECT 1/0
END TRY
BEGIN CATCH
    SELECT ERROR_NUMBER() AS ErrorNumber
     ,ERROR_SEVERITY() AS ErrorSeverity
     ,ERROR_STATE() AS ErrorState
     ,ERROR_PROCEDURE() AS ErrorProcedure
     ,ERROR_LINE() AS ErrorLine
     ,ERROR_MESSAGE() AS ErrorMessage;
END CATCH