我有以下查询,
INSERT INTO ProductsImages (BaseProductId, ImageId, [Order], CreatorId, CreationDateUtc, LastModifierId, LastModificationDateUtc)
SELECT @BaseProductId, Id, ??, @UserId, GETUTCDATE(), @UserID, GETUTCDATE() FROM @ImageIDs;
我在ProductsImages
表中插入多条记录。但问题是我需要为第一行插入Order = 1,为第二行插入Order = 2,依此类推。
答案 0 :(得分:4)
SQL数据没有任何固有顺序,因此您需要自己定义,您可以使用ROW_NUMBER()
SELECT @BaseProductId, Id, Row_Number() OVER (ORDER BY ....),
@UserId, GETUTCDATE(), @UserID, GETUTCDATE() FROM @ImageIDs;
您需要在语法
中指定所需的顺序答案 1 :(得分:1)
使用序列对象:
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;