动态查询上的SQL无效列错误

时间:2016-01-25 16:41:51

标签: sql-server dynamicquery

我有以下查询:

DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)

SELECT @ColumnName = ISNULL(@ColumnName + ',','') + QUOTENAME(MaxDate)
FROM (SELECT DISTINCT MaxDate FROM CustPeriodTable) AS MaxDates

SET @DynamicPivotQuery =

N'SELECT ' + @ColumnName + ' AS Test, min(rn)
FROM CustPeriodTable '

EXEC sp_executesql @DynamicPivotQuery

我为@ColumnName中的每个条目收到无效的列名错误。我正在设置一个涉及枢轴的更复杂的查询,但我试图让这个块首先运行。谁能指出这个问题可能来自哪里?

1 个答案:

答案 0 :(得分:1)

对于这些类型的问题,您需要查看动态查询的内容。而不是执行它只是选择它。

DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)

SELECT @ColumnName = ISNULL(@ColumnName + ',','') + QUOTENAME(MaxDate)
FROM (SELECT DISTINCT MaxDate FROM CustPeriodTable) AS MaxDates

SET @DynamicPivotQuery =

N'SELECT ' + @ColumnName + ' AS Test, min(rn)
FROM CustPeriodTable '

SELECT @DynamicPivotQuery

-- EXEC sp_executesql @DynamicPivotQuery

从这里你应该能够确定问题所在。