使用sp_executesql创建表并设置标识种子

时间:2013-12-11 06:35:27

标签: sql sql-server

需要在sql server中使用'sp_executesql'命令创建表并使用变量设置种子。我得到了我想要的种子并将其存储在@theSeed

DECLARE @theSeed int
SELECT @theSeed = (MAX([Id]) + 1) FROM [Person]

然后我想创建表并将此种子用作新表中的标识种子

EXEC sp_executesql N'CREATE TABLE [NewPerson] (
    [PersonId] [int] IDENTITY(5000 , 1) NOT NULL
PRIMARY KEY CLUSTERED 
(
    [PersonId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]'
GO

我需要用@theSeed中的值替换5000。感谢

2 个答案:

答案 0 :(得分:1)

    DECLARE @theSeed int
    SELECT @theSeed = (MAX([Id]) + 1) FROM [Person]
declare @sql varchar(1000) = 'CREATE TABLE [NewPerson] (
        [PersonId] [int] IDENTITY(' + @theSeed + ', 1) NOT NULL
    PRIMARY KEY CLUSTERED 
    (
        [PersonId] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]'
    EXEC sp_executesql @sql
    GO

答案 1 :(得分:1)

您可以使用DBCC CHECKIDENT命令:

--command to check the current identity value
DBCC CHECKIDENT ('NewPerson')

-- create table and reseed value with @theSeed variable:
DBCC CHECKIDENT ('NewPerson', RESEED, @theSeed)

或者您可以将动态查询编写为:

DECLARE @theSeed int
SELECT @theSeed = (MAX([Id]) + 1) FROM [Person]

declare @sql nvarchar(4000)
set @sql = 'CREATE TABLE [NewPerson] (
    [PersonId] [int] IDENTITY(' + cast(@theSeed as varchar) + ', 1) NOT NULL
PRIMARY KEY CLUSTERED 
(
    [PersonId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]'


EXEC sp_executesql @sql
GO

--command to check the current identity value
DBCC CHECKIDENT ('NewPerson', NORESEED)