【问题标题】:Autoincrement Id in a table inside an Insert statement插入语句内的表中的自动增量 ID
【发布时间】:2021-03-24 22:34:22
【问题描述】:

我需要在我的插入查询中自动增加一个 id。

 DECLARE @parts_table  TABLE( partid int,qty float,cost numeric(10,2),hrb int) /*create parts_table  */
/*Insert data to created table*/
    INSERT INTO @parts_table (partid,qty,cost,hrb)
    SELECT part_id ,unit_cost,qty,hrb_id FROM asset_parts

    Declare @product_codes Parts_Codes 
        while exists(select * from @parts_table where hrb=1 or hrb=3)
            Begin
                Insert into @product_codes(id ,code) Values(null,'')
            end

这里读取表中的所有数据,并根据我需要向 Parts_Codes 插入数据的数量。向表中插入数据时,我需要自动增加 id。 有什么办法吗?

【问题讨论】:

    标签: insert ssms auto-increment temp-tables


    【解决方案1】:

    我在这里找到了解决方案。

     Declare @count int
        Declare @partid int
        Declare @qty float
        Declare @hrb int
        Set @count=0
        DECLARE @parts_table  TABLE( partid int,qty float,cost numeric(10,2),hrb int,isprocess int) 
        Declare @product_codes Parts_Codes 
        
         INSERT INTO @parts_table (partid,qty,cost,hrb,isprocess )
         SELECT part_id ,unit_cost,qty,hrb_id,0 FROM asset_parts
        
         
        while exists(select * from @parts_table where isprocess =0)
        Begin
        select top 1 @partid=partid,@qty =qty ,@hrb=hrb 
        from @parts_table 
        where isprocess =0
         if(hrb=1 or hrb=3)
              Begin
                 While(@count <= @qty)
                    Begin
                        Insert into @product_codes(id ,code) Values(@count,'')
                        Set @count=@count+1
                    end
              end
        else
           begin
              Insert into @product_codes(id ,code) Values(@count,'')
           end
        Update @parts_table set isprocess =1
      End
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-07
      • 2013-03-06
      • 2018-06-24
      • 1970-01-01
      • 2020-06-14
      • 2014-08-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多