遍历 SQL 表中的变量来设置每条记录的 ID 号递增 1?

问题描述 投票:0回答:1
WHILE [production].[stocks].[id] = 1
BEGIN
   update [production].[stocks].[id]
set id = id + 1
END

stocks data table SQL File Directory

我试图循环遍历 id 变量,从第一个记录的 1 开始,然后迭代每个记录,为表的整个长度的每个记录添加 +1。商店和产品 id 目前是一个复合主键,但我正在尝试创建此 id 字段,这样我就可以将它们设为外键。我假设我索引不正确,还计划在 id 上放置一个带有长度函数的条件语句,以便当 id 变量满足从长度函数返回的整数时它停止循环。但是,我不知道该把它放在哪里。感谢您的帮助。

sql sql-server loops variables
1个回答
0
投票
if  exists (select * from [sys].[objects] WHERE object_id = OBJECT_ID(N'[production].[stocks]') AND [type] in (N'U'))
drop table [production].[stocks];
GO

if exists (select 1 from [sys].[schemas] where [name] = 'production')
drop schema production;
GO

create schema production;
GO

create table [production].[stocks] 
(
[store_id] int, 
[product_id] int, 
[quantity] int,
[id] int
);
GO

insert into [production].[stocks] 
values
(1,1,27,1),
(1,2,5,1),
(1,3,6,1),
(1,4,23,1),
(1,5,22,1),
(1,6,0,1),
(1,7,8,1),
(1,8,0,1),
(1,9,11,1),
(1,10,15,1),
(1,11,8,1),
(1,12,16,1),
(1,13,13,1),
(1,14,8,1),
(1,15,3,1),
(1,16,4,1),
(1,17,2,1),
(1,18,16,1),
(1,19,4,1);

with cte as 
(
select 
[rank] = row_number() over (order by [product_id], [store_id]), 
[store_id],
[product_id], 
[quantity]
from 
[production].[stocks]
)

update s 
set [Id] = cte.[rank]
from 
[production].[stocks] s 
inner join cte on cte.[store_id] = s.[store_id] and cte.[product_id] = s.[product_id] and cte.[quantity] = s.[quantity];

select * from [production].[stocks];
© www.soinside.com 2019 - 2024. All rights reserved.