我有以下动态查询:
SET @DynamicPIVOT = 'SELECT * FROM (
SELECT StudentId, IsForeNoon,Date as date1 FROM Attendance_FN_AN
) as Books
PIVOT (
Count(IsForeNoon) FOR date1 IN (' + @cols + ')
) as Result'
END
exec @DynamicPIVOT;
当我执行上述动态查询时,单引号未从正面和最后删除,以便问题出现
The name 'SELECT * FROM (
SELECT StudentId, IsForeNoon,Date as date1 FROM Attendance_FN_AN
) as Books
PIVOT (
Count(IsForeNoon) FOR date1 IN ([2015-04-16])
) as Result' is not a valid identifier.
对此有何解决方案?
答案 0 :(得分:1)
而不是exec @DynamicPIVOT;
使用exec(@DynamicPIVOT)
。
最好使用SP_EXECUTESQL。 SP_EXECUTESQL的一大优点是,它允许您创建参数化查询,如果您关心SQL注入,这非常好。