2010-09-09 107 views
2

我怎樣才能讓下面的查詢工作: -字符串轉換爲CSV格式

Declare @Ids as varchar(20); 

Set @Ids = '1,2,3,4'; 

Delete from tblProduct 
Where ProductId in (@Ids); 

回答

1
where ',' + @Ids + ',' like '%,' + cast(ProductId as varchar) + ',%' 

但嚴重的是,我會一直使用的是分裂了這個字符串,然後你內加入一個TVF使用您的表格生成ID並刪除行如下:

delete d 
from [table] d 
join dbo.fnSplitString(@Ids, ',') s on d.id = s.id 
1

您必須將查詢連接到一個字符串,然後執行該字符串。

DECLARE @Ids VARCHAR(MAX) 
SET @Ids = '1,2,3,4' 
DECLARE @QUERY VARCHAR(MAX) 

SET @QUERY= 'DELETE FROM tblProduct' + ' WHERE ProductId IN (' + @Ids + ')' 

EXEC (@QUERY) 
2

我假定ProductId的類型是整數。

CREATE Function [dbo].[FN_SPLITTER_STRING] (@IDs nvarchar(max), @SEP nvarchar(5)) 
Returns @Tbl_IDs Table (ID nvarchar(500)) As 

Begin 
-- Append comma 
Set @IDs = @IDs + @SEP 
-- Indexes to keep the position of searching 
Declare @Pos1 Int 
Declare @Pos2 Int 

Set @Pos1=1 
Set @Pos2=1 

While @Pos1<Len(@IDs) 
Begin 
    Set @Pos1 = CharIndex(@SEP,@IDs,@Pos1) 
    Insert @Tbl_IDs Select Substring(@IDs,@Pos2,@[email protected]) 
    Set @[email protected]+LEN(@SEP) 
    Set @Pos1 = @Pos1+LEN(@SEP) 
End 
Return 
End 

此功能需要一個@SEP deliminated字符串(@IDs),並返回包括ID作爲整數表:您可以按如下方式使用功能。

然後你就可以按如下方式使用該功能在您的存儲過程:

Delete from tblProduct Where ProductId in (select ID from dbo.FN_SPLITTER_STRING(@Ids,',')) 
+1

我們用這種方法有很多 - upvoted – 2010-09-09 07:52:31

+0

函數的名稱應該是FN_STRING_SPLITTER – 2010-09-09 07:59:17