使用两个或多个表更新ID

时间:2011-06-17 20:58:06

标签: sql sql-server tsql sql-server-2008

我有一个名为UID的表,数据如下:

U_ID   Urgent  Impact  Severe  Priority
1      1       1       NULL    1
2      1       2       NULL    1
3      1       3       NULL    1
4      3       4       NULL    3
5      2       2       NULL    2
6      NULL    NULL    1       NULL
7      NULL    NULL    NULL    1
8      NULL    NULL    NULL    2
9      NULL    NULL    NULL    3
10     NULL    NULL    NULL    4
11     1       NULL    NULL    NULL
12     1       1       NULL    NULL
13     1       2       NULL    NULL
14     1       2       1       NULL
15     1       3       1       NULL

我还有另一个名为STID的表,数据如下:

Priority    Impact  Urgent   ID
    3            4  3        1
    3            4  3        1
    2            2  2        1
    2            2  2        1
    2            2  2        1

并且我还有一个名为PRID的表,数据如下:

Priority   ID
1          2
2          2
2          2
3          2
4          2

我有一个名为FID的表,它包含U_ID和ID列所以我试图使用UID表中的U_ID和来自STID和PRID表的ID来插入这些列。我该怎么做?

我的最终FID表应该是这样的:

U_ID   ID
4      1
4      1
5      1
5      1
5      1
7      2
8      2
8      2
9      2
10     2

2 个答案:

答案 0 :(得分:0)

select U_ID, S.ID
from UID as U
  inner join STID as S
    on S.Pr = U.PR and
       S.Im = U.IM and
       S.Ur = U.UR
union all
select U_ID, P.ID
from UID as U
  inner join PRID as P
    on U.PR = P.PR and
       U.IM is null and
       U.UR is null

答案 1 :(得分:0)

select u.U_ID, s.ID
into #temp
from UID as u
  inner join STID as s on (u.Priority=s.Priority and u.Impact=s.Impact)
and s.Priority is not null

insert into #temp
select u.U_ID, p.ID
from UID as u
  inner join PRID as p on (u.Priority=p.Priority)
and u.U_ID not in (select U_ID from #temp)

Select * from #temp
order by U_ID

Drop Table #Temp