1

I'm trying to set IDENTITY seed parameter while creating table, getting it from a var. Something like this

DECLARE @MaxID INTEGER
SET @MaxID = (SELECT TOP 1 ID FROM dbo.ProductQuotes ORDER BY ID DESC) + 1;

CREATE TABLE [dbo].[Z](
 [ID] int PRIMARY KEY not null IDENTITY(@MaxID,1),
 [Number] int NULL,
 [Name] nvarchar(50) COLLATE Cyrillic_General_CI_AS NULL
) ON [PRIMARY]

GO

Error is "incorrect syntax near '@MaxID' (in this row [ID] int PRIMARY KEY not null IDENTITY(@MaxID,1) )

But I'm not sure it's about syntax at all. Can somebody explain me where am I wrong here? :)

6
  • 1
    You would need to use dynamic SQL for this. What is the reason for doing this? Also what version of SQL Server are you on? Commented Jun 20, 2013 at 10:45
  • this table is used as temp for a complex import process, so it needs to have correct identity seed to be innerjoined with the main table to finish the import. Could you explain a bit more about dynamic sql ?
    – Alex
    Commented Jun 20, 2013 at 10:50
  • With SQL Server 2012 you can use a SEQUENCE to ensure contiguous numbers across both tables msdn.microsoft.com/en-us/library/ff878091.aspx
    – gbn
    Commented Jun 20, 2013 at 10:57
  • @gbn - It ensures order not contiguity (as does IDENTITY) Commented Jun 20, 2013 at 11:01
  • 1
    @MartinSmith: true, but it allows IDs to be preallocated so there is no conflict on ProductQuotes (as your answer noted) and avoids dynamic SQL
    – gbn
    Commented Jun 20, 2013 at 11:02

2 Answers 2

1

This cannot be parameterised.

You would need to use dynamic SQL as below.

DECLARE @MaxID INTEGER

SELECT @MaxID = 1 + ISNULL(MAX(ID),0) FROM dbo.ProductQuotes

DECLARE @Script NVARCHAR(MAX) = 
N'
CREATE TABLE [dbo].[Z](
 [ID] int PRIMARY KEY not null IDENTITY(' + CAST(@MaxID AS NVARCHAR(10)) + ',1),
 [Number] int NULL,
 [Name] nvarchar(50) COLLATE Cyrillic_General_CI_AS NULL
) ON [PRIMARY]
'

EXEC (@Script);

I assume you will take precautions to ensure that ProductQuotes cannot be subject to any inserts during the import process.

0

Something like

DECLARE @MaxID INTEGER
DECLARE @SQL varChar(4000)
SET @MaxID = (SELECT TOP 1 ID FROM dbo.ProductQuotes ORDER BY ID DESC) + 1;

Set @SQL = 'CREATE TABLE [dbo].[Z]([ID] int PRIMARY KEY not null IDENTITY(' +
Convert(VarChar(8),@MaxID) + 
',1), [Number] int NULL, [Name] nvarchar(50) COLLATE Cyrillic_General_CI_AS NULL) ON [PRIMARY]
Exec(@sql)

Build the sql statement using the teh value of @MaxID then execute it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.