Pregunta

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.

¿Fue útil?

Solución

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

Otros consejos

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;
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top