数据透视表“语法不正确”

时间:2017-06-16 04:43:09

标签: sql sql-server pivot

我正在尝试将我的sql表组合在一起,但我收到的是“语法不正确”

Declare @pet varchar(max)

SET @pet = (select petsName from pets);

select * from pets

AS basedata

Pivot (
 count(PetID)

 for petsName in (' + @pet+ ') <-- error here
)

as pivottable

为什么我在@pet附近收到错误的语法?

由于

1 个答案:

答案 0 :(得分:1)

您需要为此

使用动态sql
DECLARE @pet VARCHAR(max)

SET @pet = (SELECT ',' + Quotename(petsName) -- Quotename is used to escape illegal characters
            FROM   pets
            FOR xml path('')); -- to concatenate the records 

SET @pet = Stuff(@pet, 1, 1, '') -- to remove the leading comma 

DECLARE @sql NVARCHAR(8000) = ''

SET @sql = '
select * from pets AS basedata
Pivot ( count(PetID)
for petsName in (' + @pet + ') ) as pivottable' 

exec sp_executesql @sql -- to execute the dynamically framed string 

您的查询中的另一个错误是,您尝试将petsName分配给@pet变量。

SET @pet = (select petsName from pets);

但变量只能存储一条记录。因此,您需要将记录连接到用逗号分隔的单个记录中。然后该变量可用于透视列表

SET @pet = (SELECT ',' + Quotename(petsName)
            FROM   pets
            FOR xml path(''));