需要一些帮助来运行此查询。它在' 201401'附近显示错误为"语法不正确。"
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT CONVERT (varchar(6), GETDATE(), 112) FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
, 1, 1, '2')
set @query='Select PO,ItemNo, Material, '+@cols+'
From
(Select PO,ItemNo, Material, qty ,PERIOD from sch_lines) myTab
PIVOT
( Sum(qty) FOR PERIOD IN ('+@cols+')
) as pvt'
execute sp_executesql @query
答案 0 :(得分:0)
这不是一个真正的答案,但它不适合评论。使用EXECUTE sp_executesql
时,您应该在引号内放置参数而不添加它们。添加参数会将代码暴露给SQL注入。
以下是如何将参数包含到sp_executesql
DECLARE @something NVARCHAR(20) = N'Hello World'
EXEC sp_executesql N'PRINT @something', N'@something varchar(20)', @something
有关更多信息,请参阅http://technet.microsoft.com/en-us/library/ms188001.aspx
根据您的代码看起来应该是这样的
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT CONVERT (varchar(6), GETDATE(), 112) FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
, 1, 1, '2')
set @query='Select PO,ItemNo, Material, @cols
From
(Select PO,ItemNo, Material, qty ,PERIOD from sch_lines) myTab
PIVOT
( Sum(qty) FOR PERIOD IN (@cols)
) as pvt'
execute sp_executesql @query, N'@cols nvarchar(max)', @cols