SQL案例问题设置变量

时间:2013-10-18 16:13:40

标签: sql-server case

为什么我不能执行以下脚本,我将如何修复它?我收到错误Inccorect syntax near '='。我是用...= 1 THEN 'D' ELSE '' END as Aset做的,但我需要在第三个Case中检查Aset和Bset,所以我声明了Aset和Bset。

declare @Aset varchar(10)
declare @Bset varchar(10)
UPDATE m
    SET m.new_name = m.new_name + ' ' + @ASet + AndSet + @BSet + ' Type'
FROM contactMaster m
inner join contact c on 
    m.contactid = c.contactid
     CROSS APPLY (
         SELECT CASE @Aset WHEN (c.category1|
                            c.category2|
                            c.category3|
                            c.category4) = 1 THEN 'C' ELSE '' End
               ,CASE @Bset WHEN (c.category5|
                            c.category6|
                            c.category7|
                            c.category8) = 1 THEN 'D' ELSE '' END
                ,CASE WHEN @BSet = 'D' and  @ASet  = 'C' THEN ' & ' ELSE '' END AS AndSet
     ) AS CA1

1 个答案:

答案 0 :(得分:1)

我没有你的表架构或数据,所以我不得不对它进行测试并且无法测试它,但看看这是否可行:

UPDATE      m
SET         m.new_name = m.new_name 
                         + ' ' 
                         + CA1.ASet 
                         + CASE WHEN 
                           (
                                CA1.Aset = 'C' AND 
                                CA1.Bset = 'D' 
                           ) 
                           THEN ' & ' ELSE '' END 
                         + CA1.BSet + ' Type'

FROM        contactMaster   m
JOIN        contact         c on m.contactid = c.contactid
CROSS APPLY (
                SELECT  CASE WHEN 
                        (
                            c.category1 |
                            c.category2 |
                            c.category3 |
                            c.category4
                        ) 
                        = 1 THEN 'C' ELSE '' END AS Aset,
                        CASE WHEN 
                        (
                            c.category5 |
                            c.category6 |
                            c.category7 |
                            c.category8
                        ) 
                        = 1 THEN 'D' ELSE '' END AS Bset
            ) AS CA1