使用级联字符串更新字段,具体取决于其他字段

时间:2013-02-05 10:28:53

标签: tsql sql-update sql-server-2012

我有以下SQL查询(简化):

UPDATE myTable
SET Phone1 = 049
    ,Phone2 = 123
    ,Class = --???
WHERE Project = 'ABC'

所以我只想为每个项目设置一些默认值' ABC'。对于Class字段,我需要以下内容:表中有5个其他字段,Class1到Class5,每个字段包含1或0.如果Class1为1,则Class应包含" C1"。如果Class1和Class3包含1,那么Class应为" C1 + C3"。如果所有ClassN字段都包含1,那么它应该是" C1 + C2 + C3 + C4 + C5"等等。

现在这也不太难:

DECLARE @Class NVARCHAR(100)
DECLARE @Class1 INT = 0
DECLARE @Class2 INT = 0
DECLARE @Class3 INT = 0
DECLARE @Class4 INT = 0
DECLARE @Class5 INT = 0

SET @Class = CASE 
        WHEN ISNULL(@Class1, 0) = 1
            THEN 'C1 + '
        ELSE ''
        END
SET @Class = ISNULL(@Class, '') + CASE 
        WHEN ISNULL(@Class2, 0) = 1
            THEN 'C2 + '
        ELSE ''
        END
SET @Class = ISNULL(@Class, '') + CASE 
        WHEN ISNULL(@Class3, 0) = 1
            THEN 'C3 + '
        ELSE ''
        END
SET @Class = ISNULL(@Class, '') + CASE 
        WHEN ISNULL(@Class4, 0) = 1
            THEN 'C4 + '
        ELSE ''
        END
SET @Class = ISNULL(@Class, '') + CASE 
        WHEN ISNULL(@Class5, 0) = 1
            THEN 'C5 + '
        ELSE ''
        END

-- Remove last +
IF (LEN(@Class) > 0)
    SET @Class = LEFT(ISNULL(@Class, ''), LEN(@Class) - 2)

SELECT @Class

但现在我只是不确定如何将这两件事情结合起来。我怎样才能将它们结合起来?

我现在最好的想法是创建一个标量值函数并返回字符串。

1 个答案:

答案 0 :(得分:1)

这个怎么样?

UPDATE myTable
SET Phone1 = 049
    ,Phone2 = 123
    ,Class = 
CASE WHEN 1 IN (Class1, Class2, Class3, Class4, Class5) THEN
LEFT(
CONCAT(
CASE WHEN ISNULL(Class1, 0) = 1 THEN 'C1 + ' ELSE '' END,
CASE WHEN ISNULL(Class2, 0) = 1 THEN 'C2 + ' ELSE '' END,
CASE WHEN ISNULL(Class3, 0) = 1 THEN 'C3 + ' ELSE '' END,
CASE WHEN ISNULL(Class4, 0) = 1 THEN 'C4 + ' ELSE '' END,
CASE WHEN ISNULL(Class5, 0) = 1 THEN 'C5 + ' ELSE '' END
)
, LEN(
CONCAT(
CASE WHEN ISNULL(Class1, 0) = 1 THEN 'C1 + ' ELSE '' END,
CASE WHEN ISNULL(Class2, 0) = 1 THEN 'C2 + ' ELSE '' END,
CASE WHEN ISNULL(Class3, 0) = 1 THEN 'C3 + ' ELSE '' END,
CASE WHEN ISNULL(Class4, 0) = 1 THEN 'C4 + ' ELSE '' END,
CASE WHEN ISNULL(Class5, 0) = 1 THEN 'C5 + ' ELSE '' END
)
) - 2)
ELSE '' END 
WHERE Project = 'ABC'