如何使用声明内部案例?

时间:2015-12-03 06:43:34

标签: sql sql-server

我想将一行中的多个结果与COALESCE合并。但是我在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

错误:

  

Msg 156,Level 15,State 1,Line 6
  关键字“SET”附近的语法不正确。

     

Msg 156,Level 15,State 1,Line 6
  关键字“FROM”附近的语法不正确。

有什么不对?

1 个答案:

答案 0 :(得分:1)

像这样:

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