我想将一行中的多个结果与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”附近的语法不正确。
有什么不对?
答案 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