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 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址