2013-12-17 38 views
-1

这里是我想用来获取所有合约id的合并函数,这些合约ID由用where子句中的合同标题以逗号分隔。合并获取ID

declare @tempContractID int 
SELECT @tempContractID = COALESCE(@tempContractID,'') + ContractID + ',' 
    FROM Icn_Contracts where title like '%t' 

    select @tempContractID as allcontrcats 

但我得到这个错误:

Conversion failed when converting the varchar value ',' to data type int.

当我使用聚结获取合同的名称则不会显示任何错误。

+0

为什么你声明一个int,但然后建立一个逗号分隔的字符串? –

回答

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,'');