0

我想在输入 Table1 的 ID (t1ID) 的存储过程中从 3 个相关表中删除行。

Table1       Table2       Table3
-------      -------      -------
t1ID         t2ID         t3ID
name         t1ID         t2ID
             blobpath1    blobpath2 

我需要获取每个已删除行的 blobpath1 和 blobpath2 的值作为过程的输出,因为我必须删除数据库外部的 blob 存储。

通常我会这样做:

Delete From [dbo].[Table3]  Where t2ID IN
(Select t2ID FROM [dbo].[Table2] Where [t1ID]= @t1ID)
Delete From [dbo].[Table2] Where [t1ID]= @t1ID
Delete From [dbo].[Table1] Where [t1ID]= @t1ID

如何输出 blobpaths?

4

2 回答 2

1

您可以创建一个临时表来存储blobpath1blobpath2值并在最后输出:

-- Create a temporary table to hold results
CREATE TABLE #tmpResults
(  blobpath  VARCHAR(100)  )

-- Get results from Table2
INSERT INTO #tmpResults (blobpath)
  SELECT  blobpath1
    FROM  Table2
    WHERE t1ID = @t1ID

-- Get results from Table3
INSERT INTO #tmpResults (blobpath)
  SELECT  t3.blobpath2
    FROM  Table3 t3
      INNER JOIN Table2 t2 ON t2.t2ID = t3.t2ID
    WHERE  t2.t1ID = @t1ID

-- Do your deletes as per your own code


-- Output temporary table
SELECT  blobpath
  FROM  #tmpResults

-- Tidy up
DELETE #tmpResults

请注意,我不确定您使用的是哪个 RDBMS,所以我假设使用的是 SQL Server。如果是另一个系统,您可能需要更改临时表语法。我还假设您的blobpath列是VARCHAR(100)- 您需要将其更改为适当的类型和大小。

执行存储过程后,您将收到一个包含单列 ( ) 的表输出,其中包含您删除blobpath的所有值。blobpath1blobpath2

于 2013-08-14T13:56:54.177 回答
1

您可以使用该OUTPUT子句相当简单地做到这一点;

BEGIN TRANSACTION;

DECLARE @blobpaths TABLE ( blobpath VARCHAR(32) );

DELETE t3 OUTPUT deleted.blobpath2 INTO @blobpaths
FROM table3 t3 
JOIN table2 t2 ON t2.t2id = t3.t2id
JOIN table1 t1 ON t1.t1id = t2.t1id 
WHERE t1.t1id = @t1ID;

DELETE t2 OUTPUT deleted.blobpath1 INTO @blobpaths
FROM table2 t2 
JOIN table1 t1 ON t1.t1id = t2.t1id
WHERE t1.t1id = @t1ID;

DELETE FROM table1 WHERE t1id = @t1ID;

SELECT blobpath FROM @blobpaths;

COMMIT TRANSACTION;

一个用于测试的 SQLfiddle

于 2013-08-14T14:57:22.747 回答