Sqlserver
 sql >> Teknologi Basis Data >  >> RDS >> Sqlserver

Bagaimana membandingkan antara waktu dalam loop sementara dalam prosedur tersimpan?

Jika Anda ingin membuat semua DATETIME nilai dalam jangka waktu [@StartDate, @EndDate] maka Anda dapat menggunakan tabel "tally" :

SET NOCOUNT ON
GO
-- DROP TABLE dbo.Numbers
CREATE TABLE dbo.Numbers (
    Num INT IDENTITY(0,1), 
    CONSTRAINT PK_Numbers_Num PRIMARY KEY (Num)
);
GO
-- It generates all values from 0 to 9999
INSERT dbo.Numbers DEFAULT VALUES 
GO 10000 -- You can insert more numbers if diff. between those two date/time values is greather than 13 days (I used a frecv. of 2 minutes to computes this maximum limit)

dan kemudian SELECT simple sederhana pernyataan

DECLARE @StartDate DATETIME2(0), @EndDate DATETIME2(0), @Frequency TINYINT
SELECT  @StartDate = '2015-04-17 11:00:00',
        @EndDate = '2015-04-17 11:15:00',
        @Frequency = 2; -- Minutes

SELECT  n.Num, 
        DATEADD(MINUTE, n.Num*@Frequency, @StartDate) AS RangeStart
        /*,
        CASE 
            WHEN DATEADD(MINUTE, (n.Num + 1)*@Frequency, @StartDate) > @EndDate
            THEN @EndDate
            ELSE DATEADD(MINUTE, (n.Num + 1)*@Frequency, @StartDate)
        END AS RangeEnd
        */
FROM    dbo.Numbers n
WHERE   n.Num <= DATEDIFF(MINUTE, @StartDate, @EndDate) / @Frequency
/*
Num         RangeStart                  RangeEnd
----------- --------------------------- ---------------------------
0           2015-04-17 11:00:00         2015-04-17 11:02:00
1           2015-04-17 11:02:00         2015-04-17 11:04:00
2           2015-04-17 11:04:00         2015-04-17 11:06:00
3           2015-04-17 11:06:00         2015-04-17 11:08:00
4           2015-04-17 11:08:00         2015-04-17 11:10:00
5           2015-04-17 11:10:00         2015-04-17 11:12:00
6           2015-04-17 11:12:00         2015-04-17 11:14:00
7           2015-04-17 11:14:00         2015-04-17 11:15:00
*/



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Microsoft SQL Server 2008 Management Studio - Masalah Sambungan/Server/Instance

  2. Di SQL Server, cara membuat while loop di pilih

  3. Perbedaan antara JOIN dan INNER JOIN

  4. EAV melalui SQL Server

  5. Permintaan rekursif SQL Server