3

我需要创建一个存储过程,该过程采用 userId 和 categoryIds 列表,并从特定表中删除任何匹配的行。

伪代码:

@categorylist int[]
@userId int

foreach(category as c in @categorylist)
{
DELETE FROM HelpWith as h
WHERE c.categoryId = h.categoryId
AND h.userId = @userId
}

现在我知道你不应该在 SQL 中使用循环(不是说这无论如何都会起作用......)有谁知道如何制作一个可以做到这一点的存储过程?

4

2 回答 2

4

从@Categorylist 中创建一个表变量

@Categorylist table (ID int)

DELETE FROM HelpWith 
WHERE categoryId IN (SELECT ID FROM @Categorylist)
AND userId = @userId
于 2013-05-17T08:07:46.287 回答
3

对于 SQL Server 和 2008+ 版本,您可以使用表值参数

CREATE TYPE Categorylist AS TABLE (ID int);
GO

CREATE PROCEDURE DoStuff
   @userId int,
   @list Categorylist READONLY
AS
...
DELETE FROM HelpWith 
      WHERE categoryId IN (SELECT ID FROM @list)
      AND userId = @userId
...
于 2013-05-17T08:15:42.023 回答