因为table是关键字
QUOTENAME
返回带有分隔符的 Unicode 字符串,分隔符的加入可使输入的字符串成为有效的 Microsoft® SQL Server™ 分隔标识符。语法
QUOTENAME ( 'character_string' [ , 'quote_character' ] ) 参数
'{character}[...n]'Unicode 字符数据字符串。character_string 是 sysname 值。'quote_character'用作分隔符的单字符字符串。可以是单引号 (')、左括号或右括号 ([]) 或者双引号 (")。如果未指定 quote_character,则使用括号。返回类型
nvarchar(129)示例
本示例采用字符串"abc[]def",并使用"["和"]"字符创建有效的 SQL Server 引用(分隔)标识符。SELECT QUOTENAME('abc[]def')下面是结果集:[abc[]]def](1 row(s) affected)注意,字符串"abc[]def"中的右括号有两个,用于表示转义符。

解决方案 »

  1.   

    table是保留关键字,如果不使用quotename()处理,会引起歧义。
      

  2.   

    --1.
    create table tb(groups char(2),item varchar(10),color varchar(10),quantity int)
    insert tb select 'aa','table','blue',124
    union all select 'bb','table','red',-23
    union all select 'bb','cup','green',-23
    union all select 'aa','chair','blue',101
    union all select 'aa','chair','red',-90
    go
    declare @s nvarchar(4000)
    set @s='select groups'
    select @s=@s
    +','+quotename(item) --<----
    +'=sum(case item when '+item--quotename(item,'''')
    +' then quantity end)'
    from tb
    group by item
    select @s=@s
    +','+quotename(color)--<----
    +'=sum(case color when '+color--quotename(color,'''')
    +' then quantity end)'
    from tb
    group by color
    select @s----------------------------
    print @s--加调试语句,答应出sql语句
    ----------------------exec(@s+' from tb group by groups')--2.print的sql语句,可以看出when后面有table,而table是系统关键字,所以会出错select groups,[chair]=sum(case item when chair then quantity end),
    [cup]=sum(case item when cup then quantity end),
    [table]=sum(case item when table then quantity end),
    [blue]=sum(case color when blue then quantity end),
    [green]=sum(case color when green then quantity end),
    [red]=sum(case color when red then quantity end)