문제

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