0

我在存储过程中的 SQL 服务器中有一个插入查询。

该表有 3 个字段ID, TileID, CountryID,这里 TileID 和 CountryID 是从其他表中获取的,并通过从表ID中选择 max(ID) 来递增。

我的查询:

declare @TileSId int
SET @TileSId= (SELECT isnull(max(Id),0)+1 from tilesorting)

insert [fiesauthentication].[dbo].tilesorting (Id,TileId,Nationality)

select @TileSId,t.Id,wc.CountryID from WebstoreCountry wc
left join tile t on t.URL = wc.URL AND t.CompanyId = wc.CompanyID   

在这里,如果我在选择中有多行,那么每行的 ID 都是相同的,我需要增加每一行的 ID。

我的输出:

在此处输入图像描述

我想要它像下面

在此处输入图像描述

4

1 回答 1

2

你可以试试这个。这将从表中获取最后插入的内容id,然后row_number()为每个新生成的行创建。通过添加它们,您将根据需要获得新的增量数字。

Begin Try
    Begin Transaction t1
      declare @TileSId int
      SET @TileSId= (SELECT isnull(max(Id),0)+1 from tilesorting WITH (TABLOCKX))
        ;with cte as 
        (
            select row_number() over (order by t.id) as Slno,t.Id,wc.CountryID 
            from WebstoreCountry wc
            left join tile t on t.URL = wc.URL AND t.CompanyId = wc.CompanyID 
        )
        Insert into tilesorting ( colid, col2 )
        select @TileSId + Slno , CountryID from cte
    commit transaction t1
End Try
Begin Catch
    Rollback transaction t1
End Catch

在这里,我们使用事务来锁定您的表以供进一步使用。您可以找到此链接以获取有关 SQL 中的事务链接的更多信息。

于 2019-08-08T05:22:16.327 回答