7

全部,我想IDENTITY根据从另一个表中获得的当前最大值开始对字段进行编号。所以我尝试了类似以下的方法

DECLARE @CurrentES INT;
SET @CurrentES = (SELECT MaxES 
                  FROM [NDB]..[TmpMaxES]) + 1;
ALTER TABLE BA 
ADD ES INT IDENTITY(@CurrentES, 1);

但这不会接受变量作为 IDENTITY 中的种子值。怎样才能达到我的要求?

谢谢你的时间。

4

4 回答 4

9

做这个和其他非变量允许的任务,可以使用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)
于 2012-07-24T11:38:31.173 回答
8

您可以使用dbcc checkidentSQL Server 的功能...

DECLARE @MAXID INT
SELECT @MAXID = MAX(ID_FIELD) FROM OLDTABLE
dbcc checkident(NEWTABLE, reseed, @MAXID)

需要注意的一点是,第三个参数(在本例中为@MAXID变量)中的值表示当前标识值 - 换句话说,在表上生成的最后一个标识值。

因此,例如,如果您希望自动创建的下一个值是100,则将第三个参数设置为99

于 2012-07-24T11:45:54.963 回答
2
--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;

或(如果 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
于 2014-05-02T14:44:00.810 回答
1

试试这样的..

SET IDENTITY_INSERT [MyTable] ON
INSERT INTO [MyTable] ... (MAX) Value from another table and other applicable record.
...
SET IDENTITY_INSERT [MyTable] OFF
于 2012-07-24T11:36:24.360 回答