简体   繁体   English

如何在大小写里面使用声明?

[英]How to use declare inside case?

I want to combine multiple results in one row with COALESCE . 我想将多个结果与COALESCE合并在一行中。 But i get problem with useing variable inside CASE : 但是我在CASE使用变量时遇到问题:

    DECLARE @combinedString VARCHAR(MAX);
    SELECT 
         CASE 
            WHEN parent.Id = child.Id THEN 
                (SET @combinedString = COALESCE(@combinedString + ', ', '') + Name 
                FROM dbo.MyChildTable WHERE Id IN (1, 2, 3, 5)
                SELECT @combinedString as RowName)  
         END
    FROM dbo.MyParentTable parent
    JOIN dbo.MyChildTable child ON child.Id= parent.Id

And error: 错误:

Msg 156, Level 15, State 1, Line 6 消息156,第15级,状态1,第6行
Incorrect syntax near the keyword 'SET'. 关键字“ SET”附近的语法不正确。

Msg 156, Level 15, State 1, Line 6 消息156,第15级,状态1,第6行
Incorrect syntax near the keyword 'FROM'. 关键字“ FROM”附近的语法不正确。

What can be wrong? 有什么事吗

Like this: 像这样:

DECLARE @combinedString VARCHAR(MAX);
SELECT 
     CASE 
        WHEN parent.Id = child.Id THEN 
            SELECT @combinedString = COALESCE(@combinedString + ', ', '') + Name 
            FROM dbo.MyChildTable WHERE Id IN (1, 2, 3, 5);
            SELECT @combinedString as RowName  
     END
FROM dbo.MyParentTable parent
JOIN dbo.MyChildTable child ON child.Id= parent.Id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM