简体   繁体   English

通过SQL中的多个表进行查找

[英]Look-up through multiple tables in SQL

I have 4 tables. 我有4张桌子。 R, T, RT_imp and RT. R,T,RT_imp和RT。

Table R (R_key, R_id)
Table T (T_key, T_id)
Table RT_imp (R_id, T_id, A,B,C)

Using these 3 tables I need to populate 4th table RT. 使用这3个表,我需要填充第4个表RT。

Table RT (R_key, T_key, A,B,C)

I need to find corresponding keys to ids. 我需要找到对应的ID键。 (R_key from R related to R_id of RT_imp, T_key from T related to T_id of RT_imp to insert into RT along with A,B,C) (R中的R_key与RT_imp的R_id相关,T中的T_key与RT_imp的T_id相关并与A,B,C一起插入RT)

I need to do this in a stored procedure. 我需要在存储过程中执行此操作。 How do I do these? 我该怎么做?

This should work. 这应该工作。 I created temp tables and aliases, but you could replace them with your table names. 我创建了临时表和别名,但是您可以将它们替换为表名。

Declare @R table (R_Key int, R_id int)
Declare @T table (T_Key int, T_id int)
Declare @RT_imp table (R_id int, T_id int, A char(1), B char(1), C char(1))
Declare @RT table (R_Key int, T_Key int, A char(1), B char(1), C char(1))

insert into @RT
    select r.R_Key
    , T_Key
    , rtimp.A
    , rtimp.B
    , rtimp.C
    from @RT_imp rtimp
    inner join @R r on r.R_id = rtimp.R_id
    inner join @T t on t.T_id = rtimp.T_id
create procedure insertdata
Declare @R table (R_Key int, R_id int)
Declare @T table (T_Key int, T_id int)
Declare @RT_imp table (R_id int, T_id int, A char(1), B char(1), C char(1))
Declare @RT table (R_Key int, T_Key int, A char(1), B char(1), C char(1))
AS
BEGIN
insert into @RT
    select r.R_Key, t.T_Key, rtimp.A, rtimp.B, rtimp.C
    from @RT_imp rtimp, @R r, @T t
where r.R_id = rtimp.R_id
and t.T_id = rtimp.T_id

END

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM