Вопрос

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