我正在尝试查询票务系统,可以同时为多个用户分配票证。
它将受让人以逗号分隔的值存储在列AH.AssignedTo_ETrack_UserID
中。
例如:429173,525304,390497
当我尝试运行以下命令时,由于逗号,JOIN
失败。
SELECT
DISTINCT(RI.ID) as REQ_NUM
,HT.FullName
FROM
RequestInfo RI
LEFT OUTER JOIN
RequestAssignInfoHistory AH ON RI.ID = AH.RequestInfo_ID
LEFT OUTER JOIN
WA_Team HT ON AH.AssignedTo_ETrack_UserID = HT.ID
错误讯息:
Msg 245,Level 16,State 1,Line 2
将nvarchar值'429173,525304,390497'转换为数据类型int时转换失败。
有关如何做到这一点的任何想法?
我只对这个系统有READ权限,所以我无法创建一个函数。
答案 0 :(得分:3)
create table Comma(commaValue varchar(50))
go
insert into Comma Values('429173,525304,390497')
insert into Comma Values('429173,525304,390497')
;WITH Split_Requests (xmlname)
AS
(
SELECT
CONVERT(XML,'<Requests><Request>'
+ REPLACE(commaValue,',', '</Request><Request>') + '</Request></Requests>') AS xmlname
FROM Comma
)
SELECT
xmlname.value('/Requests[1]/Request[1]','varchar(25)') AS [Type1],
xmlname.value('/Requests[1]/Request[2]','varchar(25)') AS [Type2],
xmlname.value('/Requests[1]/Request[3]','varchar(25)') AS [Type3]
FROM Split_Requests
现在,您可以在查询中使用此表并应用联接。还请检查 http://sqlfiddle.com/#!3/7206a/1