将字符串转换为CSV格式

时间:2010-09-09 07:11:49

标签: sql-server-2005

如何使以下查询起作用: -

Declare @Ids as varchar(20);

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

Delete from tblProduct
Where ProductId in (@Ids);

3 个答案:

答案 0 :(得分: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,@Pos1-@Pos2)
  Set @Pos2=@Pos1+LEN(@SEP)
  Set @Pos1 = @Pos1+LEN(@SEP)
 End 
 Return
End

此函数接受@SEP分隔字符串(@IDs)并返回包含ID为整数的表。

然后您可以在存储过程中使用该函数,如下所示:

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

答案 1 :(得分: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

答案 2 :(得分: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 )