SQL Server Select语句中的COALESCE

时间:2013-06-17 19:25:52

标签: sql sql-server coalesce

我有一个表“任务”,可以分配多个用户,存储在表“分配”中。

我有q COALESCE查询,将我的用户分组为一个字符串:

DECLARE @Names VARCHAR(8000)

SELECT @Names = COALESCE(@Names, '') + taskAssignment.FullName + '; '
FROM dbo.v_TaskAssignment taskAssignment
WHERE (taskAssignment.TaskId = @TaskId) 
  AND taskAssignment.AssignmentIsRemoved = 'False' 
  AND taskAssignment.FullName IS NOT NULL

SELECT @Names as Names

我对任务的查询:

SELECT Id, Summary
FROM dbo.v_Task

我希望我的任务查询还有一个字符串列,列出由分号分隔的所有用户。然而,这似乎不起作用:

DECLARE @Names VARCHAR(8000)

SELECT        
    dbo.v_Task.Id, dbo.v_Task.Summary, 
    (SELECT @Names = COALESCE(@Names, '') + taskAssignment.FullName + ';'
     FROM dbo.v_TaskAssignment taskAssignment
     WHERE (taskAssignment.TaskId = dbo.v_Task.Id) 
       AND taskAssignment.AssignmentIsRemoved = 'False' 
       AND taskAssignment.FullName IS NOT NULL
     SELECT @Names as Names) AS Assignements
FROM
    dbo.v_Task 
INNER JOIN
    dbo.v_TaskAssignment ON dbo.v_Task.Id = dbo.v_TaskAssignment.TaskId

我收到以下错误:

  

Msg 102,Level 15,State 1,Line 3
  '='附近的语法不正确。
  Msg 102,Level 15,State 1,Line 8
  ')'附近的语法不正确。

如何在我的任务选择查询中进行并获取Coalesce查询?

2 个答案:

答案 0 :(得分:2)

如果我理解您正在尝试正确执行的操作,那么使用XML PATH的方法有多简单?

SELECT Id, Summary, STUFF(
  (SELECT ';' + FullName 
   FROM v_TaskAssignment ta
   WHERE t.Id = ta.TaskId
     AND ta.AssignmentIsRemoved = 'False' 
     AND ta.FullName IS NOT NULL
   FOR XML PATH ('')), 1, 1, '') Assignments
FROM dbo.v_Task t

An SQLfiddle to test with

答案 1 :(得分:0)

CTE可以在这里工作 - 这样的事情可能

DECLARE @Names VARCHAR(8000)

; WITH Naming(Id,Names,Name) 如 ( 选择     t.Id     ,COALESCE(@ Names,'')+ ta.FullName +';'     ,名称 从     dbo.v_taskAssignment tA 加入     dbo.v_Task t 上     ta.TaskId = t.Id )

选择      T.Id,      T.Summary,      名称,      名称 从     命名N. 加入     v_Task T. 上     N.Id = T.Id