gpt4 book ai didi

sql-server - 删除两个表中 'equivalent'的数据

转载 作者:行者123 更新时间:2023-12-02 23:22:07 25 4
gpt4 key购买 nike

我需要在 SQL Server 2012 过程中基于表变量和这样声明的表执行以下伪逻辑:

DECLARE @tmp TABLE
(
ID int IDENTITY(1,1),
UserID int NOT NULL,
SgsID int NOT NULL
)

CREATE TABLE #Table1
(
ID int IDENTITY(1,1),
UserID int NOT NULL,
SgsID int NOT NULL
)
  1. 对于表变量中的每一行数据@tmp
  2. Table1 中删除 UserID/SgsID 组合与 Table1 中的 UserID/SgsID 匹配的行
  3. @tmp 中删除那些已从 Table1 中删除的 UserID/SgsID 组合

我一直在研究不同的方法,例如使用OUTPUT INTOINTERSECT,但无法编写跨两个表删除的查询(事实上我不这样做)认为这是可能的)。

我已经使用以下代码实现了上述步骤,但是,我想知道是否有 T-SQL 专业人士能够提出更简洁/有效的方法?

参见SQLFiddle for online version

CREATE TABLE #Table1
(
ID int IDENTITY(1,1),
UserID int NOT NULL,
SgsID int NOT NULL
)

INSERT INTO #Table1 (UserID, SgsID) VALUES (5, 99)
INSERT INTO #Table1 (UserID, SgsID) VALUES (10, 89)
INSERT INTO #Table1 (UserID, SgsID) VALUES (150, 79)
INSERT INTO #Table1 (UserID, SgsID) VALUES (200, 69)
INSERT INTO #Table1 (UserID, SgsID) VALUES (250, 59)
SELECT * FROM #Table1

DECLARE @tmp TABLE
(
ID int IDENTITY(1,1),
UserID int NOT NULL,
SgsID int NOT NULL
)

INSERT INTO @tmp (UserID, SgsID) VALUES (150, 79)
INSERT INTO @tmp (UserID, SgsID) VALUES (200, 69)
INSERT INTO @tmp (UserID, SgsID) VALUES (250, 59)
INSERT INTO @tmp (UserID, SgsID) VALUES (999, 49)
SELECT * FROM @tmp

DECLARE @tbl_commonRows TABLE (UserID int, SgsID int)
INSERT INTO @tbl_commonRows
(
UserID,
SgsID
)
SELECT
UserID,
SgsID
FROM
#Table1
INTERSECT
SELECT
UserID,
SgsID
FROM
@tmp

DELETE FROM
#Table1
WHERE
(ID IN (
SELECT
ID
FROM
#Table1 t1 INNER JOIN
@tbl_commonRows c ON c.UserID = t1.UserID AND c.SgsID = t1.SgsID))

DELETE FROM
@tmp
WHERE
(ID IN (
SELECT
ID
FROM
@tmp t2 INNER JOIN
@tbl_commonrows c ON c.UserID = t2.UserID AND c.SgsID = t2.SgsID))

SELECT * FROM #Table1
SELECT * FROM @tmp
DROP TABLE #Table1

最佳答案

解决方案如下:

DECLARE @tmp_ids TABLE (
id1 INT,
id2 INT
)

INSERT INTO @tmp_ids (id1, id2)
SELECT
t1.id,
t2.id
FROM Table1 t1
INNER JOIN tmp t2
on (t1.UserID = t2.UserID AND t1.SgsID = t2.SgsID)

DELETE FROM Table1
WHERE id IN (SELECT id1 FROM @tmp_ids)

DELETE FROM tmp
WHERE id IN (SELECT id2 FROM @tmp_ids)

请记住 - 我创建了物理表 tmp 和 Table1

关于sql-server - 删除两个表中 'equivalent'的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15246686/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com