Question

I have the following query,

INSERT INTO ProductsImages (BaseProductId, ImageId, [Order], CreatorId, CreationDateUtc, LastModifierId, LastModificationDateUtc)
SELECT @BaseProductId, Id, ??, @UserId, GETUTCDATE(), @UserID, GETUTCDATE() FROM @ImageIDs;

I am inserting multiple records into ProductsImages table. But the problem is that I need to insert Order = 1 for the first row, Order = 2 for the second row and so on.

Was it helpful?

Solution

SQL data doesn't have any inherent order, so you need to define it yourself, which you can do using ROW_NUMBER()

SELECT @BaseProductId, Id, Row_Number() OVER (ORDER BY ....),
@UserId, GETUTCDATE(), @UserID, GETUTCDATE() FROM @ImageIDs;

You need to specify the ordering you require in the syntax

OTHER TIPS

Use the sequence object:

create sequence dbo.seq
as int
start with 1
increment by 1;

INSERT INTO ProductsImages (BaseProductId, ImageId, [Order], CreatorId, CreationDateUtc, LastModifierId, LastModificationDateUtc)
SELECT @BaseProductId, Id, next value for dbo.seq, @UserId, GETUTCDATE(), @UserID, GETUTCDATE() FROM @ImageIDs;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top