2017-04-10 54 views
1

執行查詢時,這裏是我的代碼:一般錯誤SQLSTATE [HY000] Yii中2

$sql = " 
     SET @run_balqty :=0; 

     SELECT 
      transaction_date, 
      item_id, 
      item_description, 
      unit_id, 
      quantity, 
      (@run_balqty := @run_balqty + quantity) AS balance_qty, 
      reference_code 
     FROM 
      `report_ledger` AS ledger 
     WHERE 
      item_id = 3147 
     ORDER BY 
      transaction_date "; 

$query = Yii::$app->db->createCommand($sql)->queryAll(); 

當我試圖運行此代碼。我得到這個錯誤

SQLSTATE [HY000]:常規錯誤


現在..我的問題是:爲什麼我得到這個錯誤?我怎樣才能讓它運行?

需要幫助。謝謝。

回答

2

您正試圖獲取包含命令(SET @run_balqty :=0)的查詢的結果,該查詢不是'可捕獲的'。你必須先執行單靠命令,然後你可以調用queryAll()SELECT查詢命令:

Yii::$app->db->createCommand("SET @run_balqty :=null;")->execute(); 

$sql = " 
     SELECT 
      transaction_date, 
      item_id, 
      item_description, 
      unit_id, 
      quantity, 
      (@run_balqty := @run_balqty + quantity) AS balance_qty, 
      reference_code 
     FROM 
      `report_ledger` AS ledger 
     WHERE 
      item_id = 3147 
     ORDER BY 
      transaction_date "; 

$query = Yii::$app->db->createCommand($sql)->queryAll(); 

P.S .:使用SET聲明要小心,閱讀this

相關問題