2013-12-17 70 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,'');