简体   繁体   中英

How to use declare inside case?

I want to combine multiple results in one row with COALESCE . But i get problem with useing variable inside 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
Incorrect syntax near the keyword 'SET'.

Msg 156, Level 15, State 1, Line 6
Incorrect syntax near the keyword '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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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