从具有另一个(唯一)字段

时间:2017-03-06 13:56:16

标签: sql-server database

我正在尝试在多对多关系的联结表中添加值。

表看起来像这些(所有ID都是整数):

表A

+------+----------+
| id_A | ext_id_A |
+------+----------+
|   1  |    100   |
|   2  |    101   |
|   3  |    102   |
+------+----------+

表B 在概念上类似

+------+----------+
| id_B | ext_id_B |
+------+----------+
|   1  |    200   |
|   2  |    201   |
|   3  |    202   |
+------+----------+

表PK是id_A和id_B,因为我的联结表中的列是那些列的FK,但我必须插入只有外部ID的值(ext_id_A,ext_id_B)。

外部ID是唯一列,(因此在1:1中具有表id本身),因此使用ext_id我可以查找确切的行并获取需要插入到联结表中的id。

这是我到目前为止所做的一个例子,但看起来不像是一个优化的sql语句:

-- Example table I receive with test values
declare @temp as table (
    ext_id_a int not null,
    ext_id_b int not null
);

insert into @temp values (100, 200), (101, 200), (101, 201);

--Insertion - code from my sp
declare @final as table (
    id_a int not null,
    id_b int not null
);

insert into @final
select a.id_a, b.id_b
from @temp as t
inner join table_a a on a.ext_id_a = t.ext_id_a  
inner join table_b b on b.ext_id_b = t.ext_id_b

merge into junction_table as jt
using @final as f
on f.id_a = jt.id_a and f.id_b = tj.id_b
when not matched by target then
insert (id_a, id_b) values (id_a, id_b);

我正在考虑MERGE语句,因为我的存储过程在Table Value Parameters参数中接收数据,我还必须检查已经存在的引用。

我可以做些什么来改善这些值的插入?

1 个答案:

答案 0 :(得分:1)

无需使用@final表变量:

; with cte as (
     select tA.id_A, tB.id_B 
     from @temp t 
     join table_A tA on t.ext_id_a = tA.ext_id_A 
     join table_B tB on t.ext_id_B = tB.ext_id_B
)
merge into junction_table
using cte
on cte.id_A = junction_table.id_A and cte.id_B = junction_table.id_B
when not matched by target then
insert (id_A, id_B) values (cte.id_A, cte.id_B);