close

有一批程式從 MySQL 移轉到 MSSQL,沒有正常執行,翻了 error log,看到錯誤訊息是在執行資料庫語法時,出現「將 varchar 資料類型轉換成 datetime 資料類型時,產生超出範圍的值」。

先複習一下 MSDN 上頭,日期區間可容許的範圍:

可是我們的程式只抓資料區間在本月一日到月底之間的資料,為何會出錯?

仔細一看,原來錯誤發生在以前偷懶,月底的值直接寫死:

<?php 
$sql = "select * from table_test where this_date between '2022-" . $thisMonth . "-01' and '2022-" . $thisMonth . "-31'"; 
?>

當時用 MySQL,超過的日期會自動轉型,而落在原本的月底。

現在改一下,每月一定有 1 日,但小月不一定有 31 日。所以先用 PHP 的 date_format("t"),把月底的值算出來,再兜回去。

<?php
$startDate = new Datetime("2022/" . $thisMonth . "/01");
$finishDate = date_format($startDate , "Y/m/t 23:59:59");
$sql = "select * from table_test where this_date between '2022-" . $thisMonth . "-01' and '" . $finishDate . "'";
?>

 

 

arrow
arrow
    文章標籤
    php mssql sql server
    全站熱搜

    小攻城師 發表在 痞客邦 留言(0) 人氣()