这是我想用来获取所有以逗号分隔的合约ID的合并函数,其中包含where子句中的合约标题。
declare @tempContractID int
SELECT @tempContractID = COALESCE(@tempContractID,'') + ContractID + ','
FROM Icn_Contracts where title like '%t'
select @tempContractID as allcontrcats
但是我收到了这个错误:
将varchar值','转换为数据类型int。
时转换失败
当我使用coalesce获取合约名称时,它不会显示任何错误。
答案 0 :(得分:0)
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,'');