COUNT字段不正确或语法错误

时间:2015-12-04 13:35:58

标签: sql-server pdo

当我收到以下错误消息

时会出现什么错误
  

致命错误:未捕获的异常' PDOException' with message' SQLSTATE [07002]:[Microsoft] [SQL Server的ODBC驱动程序11] COUNT字段不正确或语法错误' ...

这是我使用

的查询
$sql = $pdo->prepare("SELECT stockamount, stockname, stockbalance.stockid, SUM(ABS(reservationtransaction.stockquantity)) AS reservedamount FROM stockbalance
    JOIN stock ON stockbalance.stockid = stock.stockid
    LEFT JOIN reservationtransaction ON reservationtransaction.articleid = :artid
    WHERE stockbalance.articleid = :artid AND ((changeddate > DATEADD(yy,-1,GETDATE()) AND inventorydate > DATEADD(yy,-1,GETDATE())) OR stockbalance.stockamount <> 0)
    GROUP BY stockbalance.stockid");
$sql->bindValue(':artid', $productId);
$sql->execute();

我搜索了SO中的问题,但没有人相似或有帮助 提前谢谢。

编辑:使用Microsoft SQL Server Management Studio执行此查询时,此查询正常,但在使用PDO时,我收到错误。

4 个答案:

答案 0 :(得分:22)

  

SQLBindParameter中指定的参数数量小于   包含在SQL语句中的参数数量   * StatementText。调用SQLBindParameter时将ParameterValuePtr设置为空指针,StrLen_or_IndPtr未设置为SQL_NULL_DATA或   SQL_DATA_AT_EXEC和InputOutputType未设置为SQL_PARAM_OUTPUT,因此   SQLBindParameter中指定的参数数量   大于包含的SQL语句中的参数数量   在* StatementText中。 SQLExecute Function

占位符必须具有唯一的名称,即使它们具有相同的值

$sql = $pdo->prepare("SELECT stockamount, stockname, stockbalance.stockid, SUM(ABS(reservationtransaction.stockquantity)) AS reservedamount FROM stockbalance
JOIN stock ON stockbalance.stockid = stock.stockid
LEFT JOIN reservationtransaction ON reservationtransaction.articleid = :artid
WHERE stockbalance.articleid = :artid2 AND ((changeddate > DATEADD(yy,-1,GETDATE()) AND inventorydate > DATEADD(yy,-1,GETDATE())) OR stockbalance.stockamount <> 0)
GROUP BY stockbalance.stockid");
$sql->bindValue(':artid', $productId);
$sql->bindValue(':artid2', $productId);
$sql->execute();

答案 1 :(得分:2)

另一种可能性,如果您想避免多次提供数据(用正确的数据类型替换@artid的数据类型):

{{1}}

这只适用于支持DECLARE语句的RDBMS。

答案 2 :(得分:1)

所有不在任何算术函数中的列都必须包含在GROUP BY子句中。见下文:

SELECT stockamount, 
       stockname, 
       stockbalance.stockid, 
       Sum(Abs(reservationtransaction.stockquantity)) AS reservedamount 
FROM   stockbalance 
       INNER JOIN stock 
               ON stockbalance.stockid = stock.stockid 
       LEFT JOIN reservationtransaction 
              ON reservationtransaction.articleid = :artid 
WHERE  stockbalance.articleid = :artid 
       AND ( ( changeddate > Dateadd(yy, -1, Getdate()) 
               AND inventorydate > Dateadd(yy, -1, Getdate()) ) 
              OR stockbalance.stockamount <> 0 ) 
GROUP  BY stockamount, 
          stockname, 
          stockbalance.stockid 

答案 3 :(得分:0)

尽管GROUP BY通常是COUNT问题的元凶,但我在SSRS中遇到了主题错误,这是由于SSRS数据集查询和参数之间的不匹配。解决方案是确保查询中的每个WHERE都有对应的数据集参数。 (我错过了一个。)