这些是以下参数&用于执行动态sql查询的表变量:
声明
DECLARE @sQuery VARCHAR(MAX)
DECLARE @FYear NVARCHAR(10)='2016-2017'
DECLARE @TYear NVARCHAR(10)='2016-2018'
DECLARE @CLAIMSUM TABLE
(
ClaimType NVARCHAR(MAX),
JAN DECIMAL(19,6),
FEB DECIMAL(19,6),
MAR DECIMAL(19,6),
APR DECIMAL(19,6),
MAY DECIMAL(19,6),
JUN DECIMAL(19,6),
JUL DECIMAL(19,6),
AUG DECIMAL(19,6),
SEP DECIMAL(19,6),
OCT DECIMAL(19,6),
NOV DECIMAL(19,6),
DEC DECIMAL(19,6),
TOTAL DECIMAL(19,6)
)
动态SQL查询
SET @sQuery=N'SELECT C1.ClaimType,
SUM(C1.JAN) AS ''JAN '+@FYear+'-'+@TYear+''',SUM(C1.FEB) AS ''FEB '+@FYear+'-'+@TYear+''',SUM(C1.MAR) AS ''MAR '+@FYear+'-'+@TYear+''',
SUM(C1.APR) AS ''APR '+@FYear+'-'+@TYear+''',SUM(C1.MAY) AS ''MAY '+@FYear+'-'+@TYear+''',SUM(C1.JUN) AS ''JUN '+@FYear+'-'+@TYear+''',
SUM(C1.JUL) AS ''JUL '+@FYear+'-'+@TYear+''',SUM(C1.AUG) AS ''AUG '+@FYear+'-'+@TYear+''',SUM(C1.SEP) AS ''SEP '+@FYear+'-'+@TYear+''',
SUM(C1.OCT) AS ''OCT '+@FYear+'-'+@TYear+''',SUM(C1.NOV) AS ''NOV '+@FYear+'-'+@TYear+''',SUM(C1.DEC) AS ''DEC '+@FYear+'-'+@TYear+''',
SUM(C1.TOTAL) AS ''TOTAL''
FROM @CLAIMSUM C1 GROUP BY C1.ClaimType';
EXECUTE @sQuery
错误 执行此查询时,我收到以下错误:
The name 'SELECT C1.ClaimType,
SUM(C1.JAN) AS 'JAN 2016-2017',SUM(C1.FEB) AS 'FEB 2016-2017',SUM(C1.MAR) AS 'MAR 2016-2017',
SUM(C1.APR) AS 'APR 2016-2017',SUM(C1.MAY) AS 'MAY 2016-2017',SUM(C1.JUN) AS 'JUN 2016-2017',
SUM(C1.JUL) AS 'JUL 2016-2017',SUM(C1.AUG) AS 'AUG 2016-2017',SUM(C1.SEP) AS 'SEP 2016-2017',
SUM(C1.OCT) AS 'OCT 2016-2017',SUM(C1.NOV) AS 'NOV 2016-2017',SUM(C1.DEC) AS 'DEC 2016-2017',
SUM(C1.TOTAL) AS 'TOTAL'
FROM @CLAIMSUM C1 GROUP BY C1.ClaimType' is not a valid identifier.
答案 0 :(得分:0)
我已将EXECUTE @sQuery
替换为EXECUTE (@sQuery)
,现在工作正常。