简体   繁体   English

循环遍历表中的每个值并将该值作为参数提供给函数

[英]Loop through each value in a table and supply that value as a parameter to a function

I need to loop through each value in #TempTable and use that value as a parameter for MyFunction我需要遍历#TempTable每个值并将该值用作MyFunction的参数

Function MyFunction simply returns another column based on ID_col in #TempTable函数MyFunction仅根据ID_col中的#TempTable返回另一列

IF OBJECT_ID('tempdb..#TempTable') IS NOT NULL DROP TABLE #TempTable
select 'ID1' as ID_col
into #TempTable
union select all 'ID2'
union select all 'ID3'

DECLARE @PriorID_col varchar(50)
DECLARE @ReturnVal varchar(50) = ''

SELECT TOP 1 PriorID_col = #TempTable.ID_col

-- here I need to loop through each ID_col in #TempTable and supply it as a parameter to "MyFunction"
WHILE MyFunction(#TempTable.ID_col) IS NOT NULL 
 BEGIN
        SET @PriorID_col = MyFunction(@PriorID_col)
    END
-- querying ID from real table based on variable @PriorID_col
SELECT TOP 1 @ReturnVal = ID
FROM         MyTable
WHERE        MyTable.ID = @PriorID_col

But I am unable to loop through each value in a #TempTable .但我无法遍历#TempTable每个值。 What am I doing wrong here?我在这里做错了什么?

I don't think your logic quite works, and your union all certainly doesn't.我不认为你的逻辑很有效,你的union all当然也没有。 You are getting a value for each row in the temp table, but only using one of those values to obtain the return value, and there doesn't appear to be any relationship between them.您正在为临时表中的每一行获取一个值,但仅使用其中一个值来获取返回值,并且它们之间似乎没有任何关系。

Anyway I have shown the basic premise for iterating through the rows in a temp table.无论如何,我已经展示了遍历临时表中的行的基本前提。 Essentially...本质上...

  1. Get the top row获取第一行
  2. Do something with it用它做点什么
  3. Delete it删除它
IF OBJECT_ID('tempdb..#TempTable') IS NOT NULL DROP TABLE #TempTable;

SELECT 'ID1' AS ID_col
INTO #TempTable
UNION ALL SELECT 'ID2'
UNION ALL SELECT 'ID3';

DECLARE @ID_col VARCHAR(50), @PriorID_col VARCHAR(50), @ReturnVal VARCHAR(50) = '';

-- here I need to loop through each ID_col in #TempTable and supply it as a parameter to "MyFunction"
WHILE EXISTS (SELECT 1 FROM #TempTable.ID_col)
BEGIN
    SELECT TOP 1 @ID_col = ID_col #TempTable.ID_col;
    SET @PriorID_col = dbo.MyFunction(@ID_col)
    DELETE FROM #TempTable.ID_col WHERE ID_col = @ID_col
END;

-- querying ID from real table based on variable @PriorID_col
SELECT TOP 1 @ReturnVal = ID
FROM MyTable
WHERE MyTable.ID = @PriorID_col;

Just wondering, wouldn't simple SELECT ... WHERE work for this scenario.只是想知道,简单的SELECT ... WHERE不会适用于这种情况。

SELECT 'ID1' AS ID_col
INTO #TempTable
UNION ALL SELECT 'ID2'
UNION ALL SELECT 'ID3';

SELECT *
FROM MyTable
WHERE MyTable.Id IN (SELECT MyFunction(@ID_col) FROM #TempTable)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM