简体   繁体   English

使用PDO驱动程序PHP在SQL服务器查询中的While循环

[英]While loop in a sql-server query using PDO driver PHP

I´m trying to query to a sql-server database making a while loop through PDO driver from Microsoft for PHP but it is not looping, it only returns one row. 我正在尝试查询一个sql-server数据库,并通过Microsoft的PDO驱动程序对PHP进行了while循环,但没有循环,它仅返回一行。

I have tried making the same query inside the Microsoft SQL Server Managment Studio and did get the results, I mean, it iterated and get all the rows. 我试过在Microsoft SQL Server Managment Studio中进行相同的查询,但确实得到了结果,我的意思是,它进行了迭代并获得了所有行。

Declare @startDate Datetime
Declare @finishDate Datetime
set @startDate = '2019-07-01 06:00:00.000'
set @finishDate = '2019-07-23 06:00:00.000'

Declare @date01 Datetime
Declare @date02 Datetime
set @date01 = @startDate 
set @date02 = @date01 + 1

WHILE @date01 < @finishDate 
BEGIN
    SELECT
        SUM ([col1] * [col2]) as 'val'
    FROM table
    Where [colDateTime] >= @date01 
            and [colDateTime] <= @date02 

    SET @date01 = @date01 + 1;
    SET @date02 = @date02 + 1;
END;

When doing the query through PDO I´m only getting one row but I should get like 23 rows. 通过PDO进行查询时,我只会得到一行,但我应该得到23行。

Like I mentioned in the comments using a WHILE seems like the wrong idea here. 就像我在评论中提到的使用WHILE一样,这似乎是一个错误的主意。 Loops are very slow in SQL Server and should be avoided when there a dataset approach is going to give a far more performant result. 在SQL Server中,循环非常慢,在使用数据集方法可以提供更好性能的结果时,应避免循环。

If I understand your goal correctly, you can use a Tally Table (I use an Inline here) to create all the dates, and then do everything in one go like this: 如果我正确理解了您的目标,则可以使用理货表格(此处使用内联)创建所有日期,然后像下面这样一次性完成所有操作:

DECLARE @startDate datetime;
DECLARE @finishDate datetime;
SET @startDate = '2019-07-01T06:00:00.000';
SET @finishDate = '2019-07-23T06:00:00.000';

DECLARE @D int = DATEDIFF(DAY, @startDate, @finishDate)+1;

WITH N AS(
    SELECT N
    FROM (VALUES(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL))N(N)),
Tally AS(
    SELECT TOP (@D) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) -1 AS I
    FROM N N1, N N2, N N3), --1,000 days max
Dates AS(
    SELECT DATEADD(DAY, T.I, @startDate) AS StartDate,
           DATEADD(DAY, T.I+1, @startDate) AS FinishDate
    FROM Tally T)
SELECT D.StartDate,
       SUM(T.[col1] * T.[col2]) AS Val
FROM Dates D
     JOIN [table] t ON t.colDateTime >= D.StartDate
                   AND t.colDateTime < D.FinishDate
GROUP BY D.StartDate;

If you want a row, regardless of if there are values for that date, then change the JOIN to a LEFT JOIN (and wrap the SUM in an ISNULL ). 如果要排一行,无论该日期是否有值,请将JOIN更改为LEFT JOIN (并将SUM包装在ISNULL )。

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

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