J K*_*J K 4 sql sql-server stored-procedures
我对存储过程完全不熟悉.这次,我需要在MS SQL中创建一个存储过程.
假设我有下表.
Table name: ListOfProducts
--------------------------
SomeID, ProductID
34, 4
35, 8
35, 11
Run Code Online (Sandbox Code Playgroud)
如何传递SomeID.使用此SomeID从表ListOfProducts中选择记录集.然后遍历此记录集.
假设我传入SomeID = 35.
因此,记录集将返回带有SomeID 35的2条记录.在循环中,我将获得ProductID 8和11,它将用于从另一个表中执行另一个选择.
存储过程应返回第二个选择的结果.
如何在MS SQL存储过程中执行此操作?
对不起,对于这个新手问题.谢谢你的帮助.
小智 7
如果你想循环记录.你可以这样做:
--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
Run Code Online (Sandbox Code Playgroud)
小智 0
做这样的事情:
Declare @ID int
SET @ID = 35
SELECT
p.SomeID
,p.ProductID
FROM ListOfProducts p
WHERE p.SomeID = @ID
-----------------------
--Or if you have to join to get it
Declare @ID int
SET @ID = 35
SELECT
c.SomeID
,p.ProductID
,p.ProductName
FROM ListOfProducts p
INNER JOIN categories c on p.ProductID = c.SomeID
WHERE p.SomeID = @ID
Run Code Online (Sandbox Code Playgroud)