2012-03-22 21 views
1

我們想設置使用設置標識種子到一個動態值

DBCC CHECKIDENT(「mytable的」,RESEED,0)

但我們udner的印象是服務帳戶它運行的是,標識種子必須將代碼分配給db_ddladmin角色才能執行此操作。這是真的?如果是這樣,由於政策,這對我們來說是不行的。

如果是這樣,這是我正在考慮一種替代方案:

--Create a test table 


/****** Object: Table [dbo].[People2] Script Date: 03/22/2012 19:07:12 ******/ 
SET ANSI_NULLS ON 
GO 

SET QUOTED_IDENTIFIER ON 
GO 

SET ANSI_PADDING ON 
GO 

CREATE TABLE [dbo].[People2](
    [PersonId] [int] IDENTITY(1,1) NOT NULL, 
    [LastName] [varchar](50) NOT NULL, 
    [FirstName] [varchar](50) NOT NULL, 
CONSTRAINT [PK_People2] 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 

SET ANSI_PADDING OFF 
GO 


---Proof of concept 

declare @seed int = 1000 --Set the seed 

SET IDENTITY_INSERT People2 ON 

--Insert a dummy record to increment the identity counter to 1 less than the value that we really want 
Insert into people2 
(PersonId, LastName,FirstName) 
values 
(@seed-1, 'temp','dummy') 

SET IDENTITY_INSERT People2 OFF 

--Delete the record that we just inserted (for no otehr purpose than setting the seed) 
delete from People2 where personid = @seed-1 

--Do your normal code to populate the People2 dest table 
Insert into people2 
(LastName,FirstName) 
values 
('Jones','John') 

--Verify that the seed was set to the value we wanted 

select * from People2 

其他方面的考慮插入,我們創建一個使用包含來自變量所採取的身份種子值動態SQL臨時表。

不太有吸引力的方法是手動通過記錄並手動增加ID,而不是自動列。

Tally表是一種可能性,但令我感到困惑。

對此提出建議?

+0

首先,如果你不確定的權限,只檢查文檔:HTTP:// MSDN .microsoft.com/en-us/library/ms176057.aspx其次,如果你能解釋爲什麼你需要這樣做,它會有所幫助,因爲它不明白你爲什麼關心目前的身份價值。身份值旨在用於人造密鑰,其中實際值無關緊要。 – Pondlife 2012-03-23 08:34:14

回答

2

如果您允許在表格上擁有ALTER權限,則可以使用SET IDENTITY_INSERT作爲第一個值。這會爲你更新種子。

從上面關於使用SET IDENTITY_INSERT的環節:

If the value inserted is larger than the current identity value for the table, 
SQLServer automatically uses the new inserted value as the current identity value 
0

爲什麼不

CREATE TABLE [dbo].[People2](
[PersonId] [int] IDENTITY(1000,1) NOT NULL, ... 
+0

假設「檢查號碼」是表格的標識列,並且我知道我有一百萬個檢查要寫入,並且我不知道啓動#會是什麼,直到我運行該過程。 – ChadD 2012-03-23 16:10:46

+0

如果你傳遞一個變量,那麼什麼阻止你在create語句中使用該變量。如果這是輸入數據,那爲什麼是IDENTITY? – Paparazzi 2012-03-26 02:42:52