I wrote a script against SQL 2008 which worked fine:
INSERT INTO ITEM_TABLE VALUES((SELECT ISNULL(MAX(PK_COLUMN),0) + 1
FROM ITEM_TABLE), 'Data 1', @HeadSeq)
INSERT INTO ITEM_TABLE VALUES((SELECT ISNULL(MAX(PK_COLUMN),0) + 1
FROM ITEM_TABLE), 'Data 2', @HeadSeq)
...
INSERT INTO ITEM_TABLE VALUES((SELECT ISNULL(MAX(PK_COLUMN),0) + 1
FROM ITEM_TABLE), 'Data 73', @HeadSeq)
However in 2005 it gives this error for each line:
Subqueries are not allowed in this context. Only scalar expressions are allowed.
Is there a better way of solving this rather than doing the following? (which would would make slotting one in the middle difficult)
DECLARE @SequenceCounter INT
SELECT @SequenceCounter = ISNULL(MAX(PK_COLUMN),0) FROM ITEM_TABLE
INSERT INTO ITEM_TABLE VALUES(@SequenceCounter + 1, 'Data 1', @HeadSeq)
INSERT INTO ITEM_TABLE VALUES(@SequenceCounter + 2, 'Data 2', @HeadSeq)
...
INSERT INTO ITEM_TABLE VALUES(@SequenceCounter + 73, 'Data 73', @HeadSeq)
I am aware this should be solved by first inserting the data into a table with an automatic primary key, and then transfer the data from one table to the other, I am looking for the best “script only” solution.
Thanks
Lee
As you’ve found, subqueries weren’t allowed in the
VALUESlist prior to SQL 2008. However there is an easy workarond: