PDO sqlsrv不会在最后

时间:2018-04-04 03:54:59

标签: php pdo

我试图在sql server查询中使用PDO和while循环语句插入到数据库但是while循环没有运行到最后虽然它可以正常使用简单查询,但我只使用XAMPP来运行服务器。 / p>

这里我的脚本插入2017-01-01至2018-01-01(yyyy-MM-dd)的所有日期:

try{
    $dsn = "sqlsrv:Server=MyServer,1433;Database=MyDB;";   
    $db = new PDO($dsn, "sa", "MyPassword"); 
    $db->setAttribute (PDO::SQLSRV_ATTR_QUERY_TIMEOUT, 60); 

    $query = "DELETE FROM TEST

              declare @TempDate as date
              declare @FDate as date = Cast('2017-01-01' as date)
              declare @TDate as date = Cast('2018-01-01' as date)
              declare @DayInMonthList as Table(AllDayDate varchar(8))

              BEGIN
                   SET @TempDate = @FDate
                   WHILE(@TempDate < @TDate)
                   BEGIN
                        INSERT INTO TEST(FromDate, ToDate, TempDate) VALUES(@FDate, @TDate, @TempDate)
                        SET @TempDate =DateAdd(day, 1, @TempDate) 
                   END
              END";

        $cmd = $this->db->prepare($query); 
        if(!$cmd->execute()){
            throw new PDOException ($cmd->errorInfo());
        } 
}catch(PDOException $e) {
    die("Error connecting to SQL Server: " . $e->getMessage());
} 

此脚本插入大约120行没有任何错误,我的代码有什么问题?请帮帮我!

1 个答案:

答案 0 :(得分:0)

试试这个

try{
    $dsn = "sqlsrv:Server=MyServer,1433;Database=MyDB;";   
    $db = new PDO($dsn, "sa", "MyPassword"); 
    $db->setAttribute (PDO::SQLSRV_ATTR_QUERY_TIMEOUT, 200); 
    $db->setAttribute ( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    $db->beginTransaction();
    $query = "DELETE FROM TEST

              declare @TempDate as date
              declare @FDate as date = Cast('2017-01-01' as date)
              declare @TDate as date = Cast('2018-01-01' as date)
              declare @DayInMonthList as Table(AllDayDate varchar(8))

              BEGIN
                   SET @TempDate = @FDate
                   WHILE(@TempDate < @TDate)
                   BEGIN
                        SET NOCOUNT ON;
                        INSERT INTO TEST(FromDate, ToDate, TempDate) VALUES(@FDate, @TDate, @TempDate)
                        SET @TempDate =DateAdd(day, 1, @TempDate) 
                   END
              END";

        $cmd = $db->prepare($query); 
        if(!$cmd->execute()){
            throw new PDOException ($cmd->errorInfo());
        }
        $db->commit();
}catch(PDOException $e) {
    die("Error connecting to SQL Server: " . $e->getMessage());
}

执行PDO执行时始终执行beginTransaction和commit,如下所示。

$db->beginTransaction();
$db->commit();

此外,您必须在insert语句之前添加以下代码,以便在插入时停止循环。

SET NOCOUNT ON;

我希望这会对你有所帮助。如果您有任何问题或疑虑,请告诉我。