I need to execute the following pseudo logic in a SQL Server 2012 procedure based on a table variable and a table declared as such:
DECLARE @tmp TABLE
(
ID int IDENTITY(1,1),
UserID int NOT NULL,
SgsID int NOT NULL
)
CREATE TABLE
(
ID int IDENTITY(1,1),
UserID int NOT NULL,
SgsID int NOT NULL
)
- For each row of data in a table variable
@tmp - Remove rows from
Table1where combinations UserID/SgsIDmatch UserID/SgsIDinTable1 - Delete those
UserID/SgsIDcombinations from @tmpthat were removed fromTable1
I have studied various approaches, such as using OUTPUT INTOand INTERSECT, but I canโt write a query that removes over two tables (in fact, I donโt think it is even possible).
I followed the steps above using the following code, however I was wondering if any T-SQL pro could offer a more concise / efficient approach?
SQLFiddle -
CREATE TABLE
(
ID int IDENTITY(1,1),
UserID int NOT NULL,
SgsID int NOT NULL
)
INSERT INTO
INSERT INTO
INSERT INTO
INSERT INTO
INSERT INTO
SELECT * FROM
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
INTERSECT
SELECT
UserID,
SgsID
FROM
@tmp
DELETE FROM
WHERE
(ID IN (
SELECT
ID
FROM
@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
SELECT * FROM @tmp
DROP TABLE