简体   繁体   English

如何在SQL Server中执行带日期的While循环?

[英]How to Perform While loop with Date in SQL Server?

I want to insert records by date through loop. 我想通过循环按日期插入记录。 This is what I tried. 这就是我尝试过的。

DECLARE @str VARCHAR(500) = '1400,2001,2400,1201,1001,1302'

DECLARE @startDate datetime = '2015-01-01 00:00:00'
DECLARE @endDate datetime = '2015-01-01 23:59:59'

WHILE (@startDate<='2015-01-31 00:00:00')
BEGIN

    WHILE LEN(@str) > 0
    BEGIN
        DECLARE @storeid VARCHAR(100)
        IF CHARINDEX(',',@str) > 0
            SET  @storeid = SUBSTRING(@str,0,CHARINDEX(',',@str))
        ELSE
            BEGIN
            SET  @storeid = @str
            SET @str = ''
            END
            Print @storeid
            Print @startDate

        SET @str = REPLACE(@str,@storeid + ',' , '')
        END
     SET @startDate = @startDate+1;
 END

OUTPUT 输出值

 1400
 Jan  1 2015 12:00AM
 2001
 Jan  1 2015 12:00AM
 2400
 Jan  1 2015 12:00AM
 1201
 Jan  1 2015 12:00AM
 1001
 Jan  1 2015 12:00AM
 1302
 Jan  1 2015 12:00AM

But it's not working. 但这不起作用。 Simply it inserts only one time. 只需插入一次即可。 It doesn't continue. 它不会继续。 Thanks 谢谢

EDIT: The question was drastically changed in the grace period. 编辑:在宽限期内,该问题已发生重大变化。 This is an answer to the original question. 这是对原始问题的解答。

You don't need a loop at all (in fact, you really should almost never need loops in SQL). 您根本不需要循环(实际上,您几乎绝对不需要SQL中的循环)。

You can do this by generating the date list with a tally table, and doing a JOIN to it on your INSERT : 您可以通过使用统计表生成日期列表,然后在INSERT上对其进行JOIN来实现此目的:

Declare @FromDate   Date = '2015-01-01',
        @ToDate     Date = '2015-01-31'


;With   E1(N) As (Select 1 From (Values (1), (1), (1), (1), (1), (1), (1), (1), (1), (1)) DT(N)),
        E2(N) As (Select 1 From E1 A Cross Join E1 B),
        E4(N) As (Select 1 From E2 A Cross Join E2 B),
        E6(N) As (Select 1 From E4 A Cross Join E2 B),
        Tally(N) As
        (
            Select  Row_Number() Over (Order By (Select Null)) 
            From    E6
        ),
        Dates As 
        (
            Select  DateAdd(Day, N - 1, @FromDate) Date
            From    Tally
            Where   N <= DateDiff(Day, @FromDate, @ToDate) + 1
        )
INSERT INTO Transaction_Info
    SELECT 
        TransactionNumber,StoreID,Time
    FROM 
        [HQMatajer].[dbo].[Transaction] T
    JOIN
        Dates   D ON D.Date = Convert(Date, T.Time)
    WHERE 
        StoreID=1302;

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

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