I have 2 tables that I need to populate with 100 rows from a remote linked database.
The first table is easy, because I can just do a simple INSERT from a SELECT.
However, I also need to populate a second table, using the cameraId (which is automatically generated) from the first table.
But when I try to run the queries, I get this error:
Incorrect syntax near 'SCOPE_IDENTITY()'
Code:
INSERT INTO dbo.camera
(
cameraId, --AUTOMATICALLY GENERATED IDENTITY SEED VALUE
productName,
productDesc,
productCode
)
SELECT CAMERA_ID, PRODUCT_NAME, PRODUCT_DESCRIPTION, PRODUCT_CODE
FROM [SQL_CANADA].[BASE].[dbo].PRODUCT
WHERE ORIGIN_ID = 19327761
WAITFOR DELAY '00:00:02';
INSERT INTO dbo.cameraLense
(
lenseId,
cameraId, --SCOPE_IDENTITY() ??
type,
materialId,
isCurrentYear,
modelNumber
)
SELECT LENSE_ID, SCOPE_IDENTITY(), LENSE_TYPE, MATERIAL_ID, IS_CURRENT_YEAR, MODEL_NUMBER
FROM [SQL_CANADA].[BASE].[dbo].PRODUCT
WHERE ORIGIN_ID = 19327761
Is there anything that I could do to make this work?
Thanks!
SCOPE_IDENTITY()is not the magic you want it to be, and shouldn't really be used. Instead, use theOUTPUTclause with your insert.There's no point creating a FK on a temp table, expect for illustration, you can ignore the warning you get back during the insert.
There's a few things going on here, so let's walk through it. First, we're declaring a table variable which we will use to hold pairs of the newly generated identity column, and something we already know about to link back to it.
Then we do an insert into the
#Camerastable. Nestled in there between theINSERTandSELECT is theOUTPUT. All we're doing here is asking for the values from the pseudo tableINSERTED` to be stuffed into it.Next we do the insert into the
#Lensestable. This time we have the data in our table variable, so we're able to join to it and collect the values we just inserted for#Camerasand reference them during our insert.Finally, we do a quick select on the tables we just inserted into to review what happened.
Going further with this, you could also use User Defined Table Types to pass in the values you're going to insert, but they do come with a warning. Essentially you can create a
UDTTto pass in a table. You define the table structure in the UDTT create, and then you can use it as if it were any other data type:You can only define them as parameters using the
READONLYtag:You cannot drop a
UDTTwhile something is referencing it, and you cannotALTER TYPEat all. This makes it a pain if you need to change them.