3

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

我有 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

我收到以下错误:

消息 102,级别 15,状态 1,第 3 行
'=' 附近的语法不正确。
消息 102,级别 15,状态 1,第 8 行
')' 附近的语法不正确。

如何在任务选择查询中获取 Coalesce 查询?

4

2 回答 2

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

一个用于测试的 SQLfiddle

于 2013-06-17T20:02:45.257 回答
0

CTE 可以在这里工作——可能是这样的

DECLARE @Names VARCHAR(8000)

;with Naming (Id, Names, Name) AS (SELECT t.Id ,COALESCE(@Names, '') + ta.FullName + ';' ,Name FROM dbo.v_taskAssignment tA JOIN dbo.v_Task t ON ta.TaskId = t.Id)

SELECT T.Id, T.Summary, Names, Name FROM Naming N JOIN v_Task T ON N.Id = T.Id

于 2013-06-17T20:11:36.673 回答