#insert #ssms #auto-increment #temp-tables
#вставить #ssms #автоинкремент #временные таблицы
Вопрос:
Мне нужно автоинкрементировать идентификатор внутри моего запроса insert.
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 .при вставке данных в таблицу мне нужно автоинкрементировать идентификатор.
Есть ли какой-либо способ сделать это?
Ответ №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