Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 从具有另一(唯一)字段的多个表中查找主ID_Sql Server_Database - Fatal编程技术网

Sql server 从具有另一(唯一)字段的多个表中查找主ID

Sql server 从具有另一(唯一)字段的多个表中查找主ID,sql-server,database,Sql Server,Database,我试图在多对多关系的连接表中添加值 表如下所示(所有ID都是整数): 表A +------+----------+ | id_A | ext_id_A | +------+----------+ | 1 | 100 | | 2 | 101 | | 3 | 102 | +------+----------+ 表B在概念上类似 +------+----------+ | id_B | ext_id_B | +------+----------+ |

我试图在多对多关系的连接表中添加值

表如下所示(所有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是唯一的列(因此在表id本身为1:1的情况下),因此有了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语句,因为我的存储过程接收表值参数中的数据,而且我还必须检查已有的引用


我能做些什么来改进这些值的插入吗?

无需使用
@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);

这就是为什么他们在学校教你正常化是的,我知道。。我没有创建这些表,但我必须找到解决方法。那么,您的方法有什么问题?我不是sql server/tsql专家,所以我只是想问是否有更好的方法解决这个问题。我会接受您的答案,因为没有其他人回答,这似乎是一个很好的建议。我不知道临时表和cte之间的区别,所以我无论如何都要感谢你是的,cte是一个重要的概念,它有时非常方便;再看看递归CTE,它们非常强大。至于我的回答,我希望这是你想要实现的。。。当心!