I have this pivot table (I only post the static version as the problem only regards the single quotes)SELECT * from(select DATEPART(year,DeliverydatePackingSlip) as Year, CASE WHEN DiffPromiseDateFirst < 0 Then '1 - too early' WHEN DiffPromiseDateFirst = 0 Then '2 - on time' ELSE '3 - too late' END as Deliveryfrom iq4bisprocess.FactOTDCustomerWHERE OTD_Exclusion = 0)aPIVOT ( COUNT(Year) For Year in ([2012],[2013],[2014],[2015])) as pvt
Now, packing everything in a string parameter I always stumble over the single quotes. I tried to replace them with CHAR(39), I tried to define a parameter for each occurrence, but always get a syntax error. What am I doing wrong?declare @sql nvarchar(max)declare @title1 nvarchar(20)declare @title2 nvarchar(20)declare @title3 nvarchar(20)set @title1 = '1 - too early'set @title2 = '2 - on time'set @title3 = '3 - too late'set @sql = 'SELECT * from(select DATEPART(year,DeliverydatePackingSlip) as Year, CASE WHEN DiffPromiseDateFirst < 0 Then ' + @title1 + ' WHEN DiffPromiseDateFirst = 0 Then ' + @title2 + ' ELSE ' + @title3 + ' END as Deliveryfrom iq4bisprocess.FactOTDCustomerWHERE OTD_Exclusion = 0)aPIVOT ( COUNT(Year) For Year in ([2012],[2013],[2014],[2015])) as pvt'exec sp_executesql @sql
This would throw:Msg 102, Level 15, State 1, Line 3Incorrect syntax near 'early'.