批量删除操作步骤不起作用

时间:2018-11-15 14:02:20

标签: c# sql asp.net sql-server stored-procedures

我有一个存储过程,如下所示:

alter procedure [dbo].[zsp_deleteEndedItems]
(
@ItemIDList nvarchar(max)
)
as
delete from 
SearchedUserItems
WHERE EXISTS (SELECT 1 FROM dbo.SplitStringProduction(@ItemIDList,',') S1 WHERE ItemID=S1.val)

像下面这样传递参数IDList:

124125125,125125125...etc etc

分割字符串函数如下所示:

ALTER FUNCTION [dbo].[SplitStringProduction]
(
  @string nvarchar(max),
  @delimiter nvarchar(5)
) RETURNS @t TABLE
(
  val nvarchar(500)
)
AS
BEGIN
  declare @xml xml
  set @xml = N'<root><r>' + replace(@string,@delimiter,'</r><r>') + '</r></root>'

  insert into @t(val)
  select 
    r.value('.','varchar(500)') as item
  from @xml.nodes('//root/r') as records(r)

  RETURN
END

这应该从ID下的“ SearcheduserItems”表中删除所有项:

124125125 and 125125125

但是出于某种原因,我做了选择将其签出:

select * from SearchedUserItems
where itemid in('124125125','125125125')

记录仍然存在...

我在这里做错了什么?有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

如评论中所述,另一种选择是使用表类型参数。这有两个假设(有些评论),但是应该可以使您走上正确的道路:

CREATE TYPE dbo.IDList AS TABLE (ItemID int NOT NULL); --Assumed int datatype;
GO

ALTER PROC dbo.zsp_deleteEndedItems @ItemIDList dbo.IDList READONLY AS

    DELETE SUI
    FROM dbo.SearchedUserItems SUI
         JOIN @ItemIDList IDL ON SUI.ItemID = IDL.ItemID;
GO

--Example of usage

DECLARE @ItemList dbo.IDList;

INSERT INTO @ItemList
VALUES(123456),(123457),(123458);

EXEC dbo.zsp_deleteEndedItems @ItemList;

GO

关于内联表值函数的问题,下面是一个示例,我很快就写下了它,它提供了下一个1000个数字的计数表:

CREATE FUNCTION dbo.NextThousand (@Start int)
RETURNS TABLE
AS RETURN

    WITH N AS(
        SELECT N
        FROM (VALUES(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL)) N(N)
    )
    SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) -1 + @Start AS I
    FROM N N1 --10
         CROSS JOIN N N2 --100
         CROSS JOIN N N3; --1,000
GO

关于iTVF,重要的是它只有一个语句,即RETURN语句。将表声明为返回类型变量,将数据插入其中,然后返回该变量,将其转换为多行TVF;表现要慢得多。