假设我们有表A和B,其中A是B
的父表表A:
ID | VAL
1 | "foo"
2 | "bar"
表B:
ID | aID
1 | 2
OK?
现在让我们加入:
select *
from A
inner join B on a.Id = b.aID
是否可以使用INTO
关键字将失败的连接记录立即存储到临时表中。使用OUTPUT子句类似的东西?
我知道这有点牵强,但也许有一种我不知道的方式。请尝试。
答案 0 :(得分:1)
联接记录失败?你的意思是不匹配的记录吗?
select *
from A
left join B on a.Id = b.ID
where b.ID IS NULL
要存储在临时表中,请在连接操作中重新创建的行中创建包含所需列的表结构,然后执行
INSERT INTO #temp
SELECT * from A
left join B on a.Id = b.ID
where b.ID IS NULL
或者如果您需要所有列,请执行select * into
SELECT * INTO #temp from A
left join B on a.Id = b.ID
where b.ID IS NULL
答案 1 :(得分:1)
CREATE TABLE ##tmp (
ID int,
VAL nvarchar(3),
IDD int,
aID int
)
CREATE TABLE ##tmp1 (
ID int,
VAL nvarchar(3)
)
;WITH TableA AS (
SELECT *
FROM (VALUES
(1, 'foo'),(2, 'bar')) as t(ID, VAL)
), TableB AS (
SELECT *
FROM (VALUES
(1, 2)) as t(ID, aID)
)
INSERT INTO ##tmp
select a.ID,
a.VAL,
b.ID AS IDD,
b.aID
from TableA a
FULL OUTER JOIN TableB B on a.Id = b.aID
DELETE FROM ##tmp
OUTPUT deleted.ID, deleted.VAL INTO ##tmp1
WHERE IDD IS NULL
##tmp
中的数据:
ID VAL IDD aID
----------- ---- ----------- -----------
2 bar 1 2
(1 row(s) affected)
##tmp1
中的数据:
ID VAL
----------- ----
1 foo
(1 row(s) affected)