任何人都可以帮我使用SQL Server 2008生成重复的序列号。假设我有一个1000行的表和一个新的字段(int)添加到表中。我只需要自动填充该特定字段,顺序号为1-100,一直到最后一行。
我有这个,但似乎它没有用。非常感谢你的帮助。
DECLARE @id INT
SET @id = 0
while @id < 101
BEGIN
UPDATE Names SET id=@id
set @id=@id+1
END
答案 0 :(得分:1)
USE tempdb
GO
DROP TABLE tableof1000rows
GO
CREATE TABLE tableof1000rows (id int identity(1,1), nb int, value varchar(128))
GO
INSERT INTO tableof1000rows (value)
SELECT TOP 1000 o1.name
FROM sys.objects o1
CROSS JOIN sys.objects o2
GO
UPDATE t1
SET nb = t2.nb
FROM tableof1000rows t1
JOIN (SELECT id, (ROW_NUMBER() OVER (ORDER BY id) % 100) + 1 as nb FROM tableof1000rows) t2 ON t1.id = t2.id
GO
SELECT *
FROM tableof1000rows
答案 1 :(得分:0)
不漂亮或优雅,但是......
while exists(select * from tbl where new_col is null)
update top(1) tbl
set new_col=(select ISNULL(max(new_col),0)+1 from tbl WHERE new_col is null)
答案 2 :(得分:0)
使用ROW_NUMBER生成一个数字。使用模数学来获得从1到100的值。
go
create table dbo.Demo1
(
DID int not null identity primary key,
RepetitiveSequentialNumber int not null
) ;
go
insert into dbo.Demo1 values ( 0 )
go 1000 -- This is just to get 1,000 rows into the table.
-- Get a sequential number.
select DID, row_number() over ( order by DID ) as RSN
into #RowNumbers
from dbo.Demo1 ;
-- Take the last two digits. This gives us values from 0 to 99.
update #RowNumbers
set RSN = RSN % 100 ;
-- Change the 0 values to 100.
update #RowNumbers
set RSN = case when RSN = 0 then 100 else RSN end ;
-- Update the main table.
update dbo.Demo1
set RepetitiveSequentialNumber = r.RSN
from dbo.Demo1 as d inner join #RowNumbers as r on r.DID = d.DID ;
select *
from dbo.Demo1 ;
答案 3 :(得分:0)
你的方式不起作用,因为你试图设置一个值而不是插入一个值。我相信你现在已经找到了解决方案,但如果没有,那就试试吧。
DECLARE @id INT
SET @id = 0
while @id < 101
BEGIN
INSERT Names select @id
set @id=@id+1
END