2009-08-14 19 views
38

Ho una tabella Orders con i seguenti campi:Impostare valore iniziale per la colonna con autoincrement

Id | SubTotal | Tax | Shipping | DateCreated

La colonna Id è impostato su autoincrement(1,1).

Questo deve essere utilizzato in un negozio di E-commerce. A volte un attuale negozio di e-commerce viene migrato alla mia piattaforma e hanno già ordini, il che potrebbe significare che il loro attuale Order.Id è, ad esempio, 9586.

Voglio che il campo autoincrement inizi da quel valore.

Come posso fare questo?

risposta

70

Da Resetting SQL Server Identity Columns:

Recupero dell'identità per la tabella Employees:

DBCC checkident ('Employees') 

riparazione del seme di identità (se per qualche motivo il database sta inserendo identità duplicate):

DBCC checkident ('Employees', reseed) 

Cambiare il seme di identità per la tabella Employees a 1000:

DBCC checkident ('Employees', reseed, 1000) 

La riga successiva inserita inizierà a 1001.

21

è necessario impostare il seme di identità a quel valore:

CREATE TABLE orders 
(
id int IDENTITY(9586,1) 
) 

Per modificare una tabella corrente:

ALTER TABLE orders ALTER COLUMN Id IDENTITY (9586, 1); 

Maggiori informazioni CREATE TABLE (Transact-SQL) IDENTITY (Property)

+3

Il comando ALTER TABLE sopra non funziona per me in Microsoft SQL Server 2012. Si dà questo errore: "Sintassi non corretta in prossimità della parola chiave 'IDENTITA'." Il comando DBCC nella risposta accettata ha funzionato correttamente però. –

9

Si noti inoltre che non è possibile impostare normalmente un valore per una colonna IDENTITY. È tuttavia possibile specificare l'identità delle righe se si imposta IDENTITY_INSERT su ON per la tabella. Per esempio:

SET IDENTITY_INSERT Orders ON 

-- do inserts here 

SET IDENTITY_INSERT Orders OFF 

Questo inserto sarà ripristinare l'identità per l'ultimo valore inserito. Da MSDN:

If the value inserted is larger than the current identity value for the table, SQL Server automatically uses the new inserted value as the current identity value.

+0

proprio quello che stavo cercando - è stato utile per popolare un database che stavo migrando da un mysql php a un'app C# MVC – pigeon

Problemi correlati