0

我有一个任意值列表,我想使用 T-SQL 删除多个表中的记录。我想在将来重新使用具有不同值列表的脚本。这仅用于调试目的(我只是想清除记录,以便可以使用新版本的软件重新导入),所以它不需要漂亮。

到目前为止,我有:

DECLARE @RequestIDList table(Request_ID nvarchar(50) NOT NULL)
INSERT INTO @RequestIDList (Request_ID) VALUES 
('00987172'), 
('01013218'), 
('01027886'), 
('01029552'), 
('01031476'), 
('01032882'), 
('01033085'), 
('01034446'), 
('01039261')
DELETE FROM Request WHERE Request_ID IN (SELECT Request_ID FROM @RequestIDList)
DELETE FROM RequestTest WHERE Request_ID IN (SELECT Request_ID FROM @RequestIDList)

它似乎有效,但有更好的方法吗?我似乎无法弄清楚如何直接使用带有 IN 子句的变量(例如“WHERE Request_ID IN @RequestIDList”)。

4

2 回答 2

2

快速脚本:

SET NOCOUNT ON

-- Temp table so it can be joined against in dynamic SQL
IF OBJECT_ID('tempdb..#RequestIDList') IS NOT NULL 
  DROP TABLE #RequestIDList
GO

CREATE TABLE #RequestIDList (Request_ID nvarchar(50) NOT NULL)
INSERT INTO #RequestIDList (Request_ID) VALUES 
('00987172'),('01013218'),('01027886'),('01029552'), 
('01031476'),('01032882'),('01033085'),('01034446'), 
('01039261')

DECLARE @TableList TABLE (TableName NVARCHAR(128) NOT NULL) 
INSERT @TableList VALUES 
('Request'),
('RequestTest')

DECLARE 
  @sqlcmd VARCHAR(4000),
  @table  VARCHAR(128)

-- Loop through the tables in your delete list
DECLARE c CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
SELECT TableName
FROM @TableList
ORDER BY TableName

OPEN c 
FETCH NEXT FROM c INTO @table
WHILE @@FETCH_STATUS = 0 
BEGIN 

  -- Assuming all tables in schema dbo
  -- Assuming all tables have column Request_ID
  SET @sqlcmd = 'DELETE FROM t FROM ' + QUOTENAME(@table) 
              + ' t JOIN #RequestIDList r ON r.Request_ID = t.Request_ID'

  -- PRINT @sqlcmd
  EXEC (@sqlcmd) 
  FETCH NEXT FROM c INTO @table
END

CLOSE c 
DEALLOCATE c

-- Clean up
DROP TABLE #RequestIDList
于 2012-07-27T03:38:49.543 回答
1

首先,您需要创建一个解析输入的函数

CREATE FUNCTION inputParser (@list nvarchar(MAX))
RETURNS @tbl TABLE (number int NOT NULL) AS
BEGIN
DECLARE @pos        int,
   @nextpos    int,
   @valuelen   int

SELECT @pos = 0, @nextpos = 1

WHILE @nextpos > 0
BEGIN
SELECT @nextpos = charindex(',', @list, @pos + 1)
SELECT @valuelen = CASE WHEN @nextpos > 0
                      THEN @nextpos
                      ELSE len(@list) + 1
                 END - @pos - 1
INSERT @tbl (number)
  VALUES (convert(int, substring(@list, @pos + 1, @valuelen)))
SELECT @pos = @nextpos
END
RETURN
END

然后在 SP 中使用该函数

CREATE PROCEDURE usp_delete
@RequestIDList varchar(50) 
AS
Begin
 DELETE FROM Request as req inner join 
 inputParser (@RequestIDList) i on req.Request_ID = i.number
End

EXEC usp_delete '1, 2, 3, 4'

有关更多详细信息,请查看本文。它解释了不同的方法,具体取决于 sql server 版本。对于 SQl server 2008,它使用 TVP,这进一步简化了输入解析器

于 2012-07-27T03:08:59.740 回答