dongzhi6382 2013-07-14 22:15
浏览 53
已采纳

在SQL Server上使用PDO时,为什么不能按列别名进行排序?

Note: the only difference in the following examples is the ORDER BY clause.

Good code:

$sql = 'SELECT [date], ? AS [name] 
FROM [transactions] 
WHERE [category_id] = 10 
GROUP BY [date] 
ORDER BY [date] ASC';

$stmt = $db->prepare($sql);
$stmt->bindValue(1, 'Test', PDO::PARAM_STR);
$stmt->execute();
$data = $stmt->fetchAll();
//returns rows in $data

Bad code:

$sql = 'SELECT [date], ? AS [name] 
FROM [transactions] 
WHERE [category_id] = 10 
GROUP BY [date] 
ORDER BY [date] ASC, [name] ASC';

$stmt = $db->prepare($sql);
$stmt->bindValue(1, 'Test', PDO::PARAM_STR);
$stmt->execute();
$data = $stmt->fetchAll();
//returns an empty array

Why is my second block of code not working? If I run either version of this query directly (in SQL Management Studio), it works either way. And if I get rid of the question mark in PHP and hardcode the value into the query (rather than binding it), that works too! What is going on here?

Update: Here is a sample PHP script that better illustrates the problem: http://snipt.org/ALhd1. In this linked sample code, I include 5 "tests." Tests #1, 2, and 4 all return results, while tests #3 and 5 do not and should illustrate the problem.

  • 写回答

2条回答 默认 最新

  • dongmei8511 2013-07-24 17:12
    关注

    I've managed to reproduce the problem with PHP 5.4 and SQL Server 2012.

    The problem seems to lie in the ODBC driver for PDO. The successful tests give the same result using both drivers, but the below uses test3 as a sample.

    Using the native SQL Server PHP driver from Microsoft (3.0) gives the correct result;

    $db = new PDO('sqlsrv:server=.\\SQLEXPRESS');
    
    array(3) { [0]=> string(5) "00000" [1]=> NULL [2]=> NULL }
    array(1) { [0]=> array(4) {
        ["date"]=> string(23) "2013-07-23 10:34:24.497"
        [0]=>      string(23) "2013-07-23 10:34:24.497"
        ["name"]=> string(4) "Test"
        [1]=>      string(4) "Test"
      }
    }
    

    ...while running the exact same code using ODBC gives your exact failed result;

    $db = new PDO('odbc:driver={SQL Server Native Client 11.0};server=.\SQLEXPRESS;Trusted_Connection=yes');
    
    array(4) { [0]=>string(5) "00000" [1]=> int(0)  
               [2]=> string(24) " ((null)[0] at (null):0)" [3]=> string(0) "" }
    array(0) { }
    

    In other words, it's not a limitation in PDO itself or in SQL Server, it's a limitation/bug in the ODBC driver.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?