我只是坚持更新下表列。请考虑以下脚本。
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
答案 0 :(得分:2)
<强>查询:强>
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;
这会使@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 |