سؤال

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.

هل كانت مفيدة؟

المحلول

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

نصائح أخرى

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;
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top