Saturday, September 27, 2014

Incorrect syntax near ')'

Debug the dynamic SQL query first prior to execution:



create PROCEDURE [dbo].[spScheduleLaborRequireByDate]
@QSDate date
AS
BEGIN
declare @cols varchar(1000), @SQL nvarchar(max)
declare @tbDate table (SDate date)

insert @tbDate
select distinct a.SDate
from (select a.SDate ,sum(a.SLabor ) as LaborRequire
from (select a.SDate ,a.SLabor from ProductionSchedule a where a.SDate >=@QSDate) a
group by a.SDate ) a order by a.SDate

set @cols =STUFF (( select ',' + a.RequireDate
from (select '[' + convert(varchar,a.SDate,1) +']' As RequireDate
from @tbDate a) a for xml path ('')),1,1,'')

SET @SQL ='Select * from (select a.SDate ,sum(a.SLabor ) as LaborRequire
from (select a.SDate ,a.SLabor from ProductionSchedule a where a.SDate >='+ @QSDate +') a
group by a.SDate ) as a pivot (sum(LaborRequire) for SDate in (' + @cols + ')) as b'

PRINT @SQL

-- EXEC sp_executeSQL @SQL

END



Dynamic SQL: http://ift.tt/1higpJb








Kalman Toth Database & OLAP Architect SQL Server 2014 Database Design

New Book / Kindle: Beginner Database Design & SQL Programming Using Microsoft SQL Server 2014







No comments:

Post a Comment