0

我只是坚持更新下表列。考虑下面的脚本。

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
4

2 回答 2

2

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')

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

结果

| 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 |
于 2012-12-13T06:13:04.283 回答
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 小提琴演示

这将使@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 |
于 2012-12-13T06:30:51.360 回答