如何在动态SQL字符串

时间:2016-08-31 05:18:37

标签: sql sql-server

这是我的代码,我在Dynamic sql字符串中使用iff函数时遇到了麻烦 SQL服务器将错误发布为"错误的语法附近'赢得了'。"帮助我。

Declare @Colname NVARCHAR (128)
Declare @SQl NVARCHAR(MAX)

set @Colname = N'Channel_Edited'

Set @SQl = N'Select '+@Colname+', Count(WonOpps) as Won, Count(LostOpps) as Lost, Count(OpenOpps) as [open]
From
    (        select '+@Colname+',
                    iif (Stage_Edited = 'won', opp_id,null) WonOpps,
                    iif (Stage_Edited = 'lost', opp_id,null) LostOpps,
                    iif (Stage_Edited = 'open', opp_id,null) OpenOpps

            From CRM_Deal2
            ) as ABC
 Group by '+@Colname

 Exec sp_executesql @SQL

1 个答案:

答案 0 :(得分:2)

更改代码中的部分

  iif (Stage_Edited = ''won'', opp_id,null) WonOpps,
                    iif (Stage_Edited = ''lost'', opp_id,null) LostOpps,
                    iif (Stage_Edited = ''open'', opp_id,null) OpenOpps