如何更新依赖于另一个表的表记录

时间:2012-12-13 06:02:40

标签: sql

我只是坚持更新下表列。请考虑以下脚本。

declare @Table1 Table  ( ID int Identity(1,1), UserCount int )
insert into @Table1 (UserCount) values (2),(3),(5)
declare @Table2 Table ( ID int Identity(1,1), Name varchar(10), IDRef int null)
insert into @Table2 (Name) values ('p1'),('p2'),('p3'),('p4'),('p5'),('p6'),('p7'),('p8'),('p9'),('p10')

结果

从@ Table1中选择*

ID          UserCount
----------- -----------
1           2
2           3
3           5

从@ Table2中选择*

ID          Name       IDRef
----------- ---------- -----------
1           p1         NULL
2           p2         NULL
3           p3         NULL
4           p4         NULL
5           p5         NULL
6           p6         NULL
7           p7         NULL
8           p8         NULL
9           p9         NULL
10          p10        NULL

根据@Table1.UserCount值,我需要使用Table2.IDRef更新@Table1.ID值。

预期结果是,

ID          Name       IDRef
----------- ---------- -----------
1           p1         1
2           p2         1
3           p3         2
4           p4         2
5           p5         2
6           p6         3
7           p7         3
8           p8         3
9           p9         3
10          p10        3

2 个答案:

答案 0 :(得分:2)

SQL Fiddle

<强>查询:

declare @Table1 Table  ( ID int Identity(1,1), UserCount int )
insert into @Table1 (UserCount) values (2),(3),(5)
declare @Table2 Table ( ID int Identity(1,1), Name varchar(10), IDRef int null)
insert into @Table2 (Name) values ('p1'),('p2'),('p3'),('p4'),('p5'),('p6'),('p7'),('p8'),('p9'),('p10')

update t2
set t2.idref = t1.id
from (
    select *, rn=row_number() over (order by id)
      from @table1 t1
      join master..spt_values v on v.type='p'
                               and v.number between 1 and t1.UserCount
) t1
join (select *, rn=row_number() over (order by id)
        from @table2
) t2 on t1.rn=t2.rn

select * from @Table2
order by id

<强> Results

| ID | NAME | IDREF |
---------------------
|  1 |   p1 |     1 |
|  2 |   p2 |     1 |
|  3 |   p3 |     2 |
|  4 |   p4 |     2 |
|  5 |   p5 |     2 |
|  6 |   p6 |     3 |
|  7 |   p7 |     3 |
|  8 |   p8 |     3 |
|  9 |   p9 |     3 |
| 10 |  p10 |     3 |

答案 1 :(得分:0)

你可以这样做:

;WITH Digits
AS
(
  SELECT n
  FROM (VALUES(1), (2), (3), (4), (5), (6), (7), (8), (9), (10)) d(n)
), TableRefs
AS
(
  SELECT 
    ID, 
    RefId = d.n,
    UserCount,
    ROW_NUMBER() OVER(ORDER BY(SELECT 1)) rownum
  FROM @table1 
  INNER JOIN Digits d ON n <= usercount
)
UPDATE t2
SET IDRef = tref.ID
FROM @table2 t2
INNER JOIN TableRefs tref ON t2.Id = tref.rownum;

SQL Fiddle Demo

这会使@table2如此:

| ID | NAME | IDREF |
---------------------
|  1 |   p1 |     1 |
|  2 |   p2 |     1 |
|  3 |   p3 |     2 |
|  4 |   p4 |     2 |
|  5 |   p5 |     2 |
|  6 |   p6 |     3 |
|  7 |   p7 |     3 |
|  8 |   p8 |     3 |
|  9 |   p9 |     3 |
| 10 |  p10 |     3 |