这是我要使用的合并函数,用于获取where子句中以逗号分隔并带有合同标题的所有合同id。
declare @tempContractID int
SELECT @tempContractID = COALESCE(@tempContractID,'') + ContractID + ','
FROM Icn_Contracts where title like '%t'
select @tempContractID as allcontrcats
但是我得到这个错误:
将varchar值','转换为数据类型int时,转换失败。
当我使用合并来获取合同名称时,它不会显示任何错误。
declare @tempContractID VARCHAR(MAX); -- you can't build a string as an int
SELECT @tempContractID = COALESCE(@tempContractID,'')
+ CONVERT(VARCHAR(11),ContractID) -- needs to be a string, as error says
+ ',' FROM dbo.Icn_Contracts -- please always use schema prefix
where title like '%t';
select @tempContractID as allcontrcats;
尽管我更喜欢这种方法,因为,如果您想依赖输出的顺序,则可以(如果ORDER BY
在上面的查询中添加,则结果的顺序仍然不确定)。
SELECT @tempContractID = STUFF((SELECT ','
+ CONVERT(VARCHAR(11), ContractID)
FROM dbo.Icn_Contracts
WHERE title LIKE '%t'
ORDER BY ContractID -- well-defined
FOR XML PATH, TYPE).value('.[1]','nvarchar(max)'),1,1,'');
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句