简体   繁体   English

sql遍历表中的每一行

[英]sql loop through each row in a table

I've created a program that generates buy and sell signals of stocks.我创建了一个程序,可以生成股票的买卖信号。 I've also created logic that tests the different signals and provides the return for each trade.我还创建了测试不同信号并为每笔交易提供回报的逻辑。

The next step is to simulate the strategy and its rules over a long period of time.下一步是在很长一段时间内模拟策略及其规则。 All information is exported to text files and imported to a table in a SQL Server database.所有信息都导出到文本文件并导入到 SQL Server 数据库中的表中。 I've realized that I need to declare a number of variables such as StartCapital , CurrentCapital , NumberOfPositions , PositionsLeft .我意识到我需要声明一些变量,例如StartCapitalCurrentCapitalNumberOfPositionsPositionsLeft One of the columns is named BuyPrice and indicates when to buy and to which price, when this occurs NumberOfPositions should be subtracted by 1.其中一列名为BuyPrice ,指示何时购买以及以哪个价格购买,发生这种情况时应将NumberOfPositions减去 1。

The column SellPrice indicates when to sell and to which price, when this occurs NumberOfPositions needs to be added by one. SellPrice列指示何时出售以及以哪个价格出售,当发生这种情况时NumberOfPositions需要加一。 The maximum of NumberOfPositions should be 5 and minimum 0. The desired result is to see how the CurrentCapital unfolds. NumberOfPositions的最大值应为 5,最小值应为 0。所需的结果是查看CurrentCapital如何展开。

I would very much appreciate any input and some kind of SQL code to start form.我非常感谢任何输入和某种 SQL 代码来启动表单。

There is another way to loop.还有另一种循环方式。 I've seen a lot of answers increment the counter by 1. However, in my experience, there is no guarantee that your ids in the dataset won't have gaps.我已经看到很多答案将计数器加 1。但是,根据我的经验,不能保证您在数据集中的 id 不会有间隙。

Here is a solution that I often use:这是我经常使用的解决方案:

declare @idColumn int

select @idColumn = min( TableID ) from Table

while @idColumn is not null
begin
    /*
        Do all the stuff that you need to do
    */
    select @idColumn = min( TableID ) from Table where TableID > @idColumn
end

Based on the caption of your question.根据您问题的标题。 This is the way I loop through each row of a table using a variable of type TABLE :这是我使用TABLE类型的变量遍历表的每一行的方式:

DECLARE
    @counter    INT = 1,
    @max        INT = 0

-- Declare a variable of type TABLE. It will be used as a temporary table.
DECLARE @myTable TABLE (
    [Id]        int identity,
    [Column1]   nvarchar(max),
    [Column2]   nvarchar(100)
)

-- Insert your required data in the variable of type TABLE
INSERT INTO @myTable
SELECT Column1, Column2
FROM [dbo].[YOUR_DATABASE_TABLE]

-- Initialize the @max variable. We'll use thie variable in the next WHILE loop.
SELECT @max = COUNT(ID) FROM @myTable

-- Loop 
WHILE @counter <= @max
BEGIN

    -- Do whatever you want with each row in your table variable filtering by the Id column
    SELECT Column1, Column2
    FROM @myTable
    WHERE Id = @counter

    SET @counter = @counter + 1
END

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

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