gpt4 book ai didi

sql - 循环遍历记录集并使用结果执行另一个 SQL 选择并返回结果

转载 作者:行者123 更新时间:2023-12-03 01:55:55 25 4
gpt4 key购买 nike

我对存储过程完全陌生。这次,我需要在 MS SQL 中创建一个存储过程。

假设我有下表。

     Table name: ListOfProducts  
--------------------------
SomeID, ProductID

34, 4
35, 8
35, 11

如何传入 SomeID。使用此 SomeID 从表 ListOfProducts 中选择记录集。然后循环遍历这个记录集。

假设我传入 SomeID = 35。

因此,记录集将返回 SomeID 35 的 2 条记录。在循环中,我将获得 ProductID 8 和 11,这将用于从另一个表中进行另一次选择。

存储过程应返回第二次选择的结果。

如何在 MS SQL 存储过程中执行此操作?

抱歉,对于这个新手问题。感谢您的帮助。

最佳答案

如果你想循环遍历记录。你可以这样做:

--Container to Insert Id which are to be iterated
Declare @temp1 Table
(
tempId int
)
--Container to Insert records in the inner select for final output
Declare @FinalTable Table
(
Id int,
ProductId int
)

Insert into @temp1
Select Distinct SomeId From YourTable

-- Keep track of @temp1 record processing
Declare @Id int
While((Select Count(*) From @temp1)>0)
Begin
Set @Id=(Select Top 1 tempId From @temp1)

Insert Into @FinalTable
Select SomeId,ProductId From ListOfProducts Where Id=@Id

Delete @temp1 Where tempId=@Id
End

Select * From @FinalTable

关于sql - 循环遍历记录集并使用结果执行另一个 SQL 选择并返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15286255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com