如何将连接范围之外的数据捕获到 tempTBL 中

how to capture the data that is outside of the join scope into a tempTBL

假设我们有 tables A 和 B,其中 A 是 B

的父 table

表A:

ID | VAL
1  | "foo"
2  |  "bar"

表B:

ID | aID
1  |  2

好吗?

现在让我们加入:

select *
from A
inner join B on a.Id = b.aID

有没有办法使用INTO关键字立即将失败的加入记录存储到临时table中。使用 OUTPUT 子句有类似的东西吗?

我知道这有点牵强,但也许有一种方法我不知道。值得尝试。

加入记录失败?您是说不匹配的记录吗?

select *
from A
left join B on a.Id = b.ID 
where b.ID IS NULL

要存储在临时 table 中,创建 table 结构,其中包含在连接操作中检索到的行中的所需列,然后执行

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
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)