我有一个1存储过程,在其中使用了以下查询:
DECLARE @product_id int
select @product_id=id from rpidata where collection_id = 354
select @product_id
它只给我最后一条记录。 现在,当我点击以下查询时,它会给我5条记录。
select id,ngj_id,tul_price from rpidata where collection_id = 354
现在我想获取所有这些记录并循环计算其他价格。 示例:
DECLARE @product_id int
for loop start //To traverse all 5 records
select @product_id=id from rpidata where collection_id = 354
select @product_id
//My custom calculation for other fields.
for loop end
我该怎么做?
答案 0 :(得分:1)
您需要表变量:
declare @producttable table (
product_id int,
ngj_id <required-type>,
tul_pric <required-type>
)
insert into @producttable (product_id)
select id, ngj_id, tul_pric
from rpidata
where collection_id = 354;
select pt.*
from @producttable pt;
答案 1 :(得分:1)
再次。循环并不是SQL中最好的主意。当您无路可走时,请去做。添加到@Yogesh的答案:
declare @producttable table (
product_id int,
ngj_id <required-type>,
tul_pric <required-type>
)
declare @count int=0
declare @num_of_rows int=0
declare @row_id = -1
insert into @producttable (product_id, ngj_id, tul_pric)
select id, ngj_id, tul_pric
from rpidata
where collection_id = 354
select @num_of_rows = count(*) from @producttable
while(@count <= @num_of_rows)
begin
select @row_id = product_id from @producttable ORDER BY product_id LIMIT 1
//rest of your code
set @count=@count+1
end