全部,我想根据从另一个表获得的当前最大值开始IDENTITY
字段的编号。所以我尝试了类似下面的内容
DECLARE @CurrentES INT;
SET @CurrentES = (SELECT MaxES
FROM [NDB]..[TmpMaxES]) + 1;
ALTER TABLE BA
ADD ES INT IDENTITY(@CurrentES, 1);
但是这不会接受变量作为IDENTITY中的种子值。如何实现我的目标?
感谢您的时间。
答案 0 :(得分:6)
执行此操作和其他非变量允许的任务,可以使用EXEC功能,如下所示:
DECLARE @CurrentES INT;
SET @CurrentES = (SELECT MaxES
FROM [NDB]..[TmpMaxES]) + 1;
DECLARE @Statement VARCHAR(200)
SET @Statement = 'ALTER TABLE BA
ADD ES INT IDENTITY(' + CAST(@CurrentES AS VARCHAR) + ', 1);'
EXEC (@Statement)
答案 1 :(得分:5)
您可以使用SQL Server的dbcc checkident
功能...
DECLARE @MAXID INT
SELECT @MAXID = MAX(ID_FIELD) FROM OLDTABLE
dbcc checkident(NEWTABLE, reseed, @MAXID)
有一点值得注意的是,第3个参数(在本例中为@MAXID
变量)中的值表示当前标识值 - 换句话说,最后一个标识值是在桌子上生成的。
因此,例如,如果您希望自动创建的下一个值为100
,请将第三个参数设置为99
。
答案 2 :(得分:1)
尝试这样的事情......
SET IDENTITY_INSERT [MyTable] ON
INSERT INTO [MyTable] ... (MAX) Value from another table and other applicable record.
...
SET IDENTITY_INSERT [MyTable] OFF
答案 3 :(得分:1)
--first variable
declare @code varchar(50);
set @code=1345688867567576;
--second variable
declare @namedb varchar(50);
set @namedb='test';
--let's you add to the identity(ID) field
SET IDENTITY_INSERT dbo.nameAndroid ON
--declaring variable to hold the next id number
declare @id int;
set @id=@@IDENTITY +1;
--clause to check if the table has the matching barcode
if not exists (select * from dbo.nameAndroid where barcode = @code)
INSERT INTO dbo.nameAndroid (id, name, barcode, [floor], Column1,Column2,Row1,Row2,Shelf,Stock,OnOrder)
VALUES ( @id,@namedb, @code, 'Value3', 'Value4','Value5','Value6','Value7','Value8',123,600);
SET IDENTITY_INSERT dbo.nameAndroid OFF;
OR(如果id列的类型为int)
declare @code varchar(50);
set @code='123211';
declare @namedb varchar(50);
set @namedb='test';
declare @floordb varchar(50);
set @floordb='test';
declare @Column1db varchar(50);
set @Column1db='test';
declare @Column2db varchar(50);
set @Column2db='test';
declare @Row1db varchar(50);
set @Row1db='test';
declare @Row2db varchar(50);
set @Row2db='test';
declare @Shelfdb varchar(50);
set @Shelfdb='test';
declare @OnOrderdb decimal(18,2);
set @OnOrderdb=10010;
declare @Stockdb decimal(18,2);
set @Stockdb=1010101;
declare @id int;
set @id=((select max(id) from dbo.nameAndroid )+1);
if not exists (select * from dbo.nameAndroid where barcode = @code)
begin
SET IDENTITY_INSERT dbo.nameAndroid ON;
INSERT INTO dbo.nameAndroid (id, name, barcode, [floor], Column1,Column2,Row1,Row2,Shelf,Stock,OnOrder)
VALUES (@id, @namedb, @code, @floordb, @Column1db,@Column2db,@Row1db,@Row2db,@Shelfdb,@OnOrderdb,@Stockdb);
SET IDENTITY_INSERT dbo.nameAndroid OFF;
end