我有3个不同的数据库,每个数据库都包含表格 我需要查询删除所有3个表中不存在的每个代码(主键)的行(不同数据库中的每个表)
类似的东西:
DELETE FROM dbA.tableX, dbB.tableY, dbC.tableZ
WHERE dbA.tableX.column <> dbB.tableY.column <> dbC.tableZ.column;
在查询运行之后,所有表应具有相同数量的具有相同主键值的行。
答案 0 :(得分:0)
由于您要从三个表中删除,因此您需要三个删除语句,但您可以将它们全部放在一个事务中。类似......
BEGIN TRANSACTION;
WITH CTE AS
(
SELECT *
FROM dbA.dbo.tableX X
INNER JOIN dbA.dbo.tableY Y ON X.Pk_Col = Y.Pk_Col
INNER JOIN dbA.dbo.tableZ Z ON Z.Pk_Col = Y.Pk_Col
)
DELETE FROM dbA.dbo.tableX
WHERE NOT EXISTS (SELECT 1
FROM CTE
WHERE dbA.dbo.tableX = C.Pk_Col)
;WITH CTE AS
(
SELECT *
FROM dbA.dbo.tableX X
INNER JOIN dbA.dbo.tableY Y ON X.Pk_Col = Y.Pk_Col
INNER JOIN dbA.dbo.tableZ Z ON Z.Pk_Col = Y.Pk_Col
)
DELETE FROM dbA.dbo.tableY
WHERE NOT EXISTS (SELECT 1
FROM CTE
WHERE dbA.dbo.tableX = C.Pk_Col)
;WITH CTE AS
(
SELECT *
FROM dbA.dbo.tableX X
INNER JOIN dbA.dbo.tableY Y ON X.Pk_Col = Y.Pk_Col
INNER JOIN dbA.dbo.tableZ Z ON Z.Pk_Col = Y.Pk_Col
)
DELETE FROM dbA.dbo.tableZ
WHERE NOT EXISTS (SELECT 1
FROM CTE
WHERE dbA.dbo.tableX = C.Pk_Col)
COMMIT TRANSACTION;
答案 1 :(得分:0)
我会简化M. Ali的答案,因为不需要从所有3个表中查询3次公共行。
BEGIN TRANSACTION;
WITH CTE AS
(
SELECT *
FROM dbA.dbo.tableX X
INNER JOIN dbA.dbo.tableY Y ON X.Pk_Col = Y.Pk_Col
INNER JOIN dbA.dbo.tableZ Z ON Z.Pk_Col = Y.Pk_Col
)
DELETE FROM dbA.dbo.tableX
WHERE NOT EXISTS (SELECT 1
FROM CTE
WHERE dbA.dbo.tableX = C.Pk_Col)
DELETE FROM dbA.dbo.tableY
WHERE NOT EXISTS (SELECT 1
FROM CTE
WHERE dbA.dbo.tableX = C.Pk_Col)
DELETE FROM dbA.dbo.tableZ
WHERE NOT EXISTS (SELECT 1
FROM CTE
WHERE dbA.dbo.tableX = C.Pk_Col)
COMMIT TRANSACTION;