我使用php pdo和SQL Server Native Client 11.0作为驱动程序。 很明显我不能使用LIMIT子句,因为它是专有的,并且在尝试选择行的范围时我一直在遇到问题。
我的设置如下:
$statement = "SELECT ROW_NUMBER() OVER (ORDER BY USERS.name DESC) AS RowNum, CASE.no, CASE.type, CASE.date, CASE.ju, USERS.name, TBRLMF.rd_rl_description FROM dbo.CASE INNER JOIN dbo.USERS ON dbo.CASE.no = dbo.USERS.case_no INNER JOIN dbo.CMSTBRLMF ON dbo.USERS.relationship = dbo.TBRLMF.code ";
if($exact == 'checked'){
$exact = '=';
}else{
$exact = 'LIKE';
}
if($searchtype == 'users'){
$statement .= " WHERE USERS.name $exact '%$searchstring%'";
}else{
$statement .= " WHERE USERS.no $exac '%$searchstring%'";
}
$statement .= " AND RowNum BETWEEN :offset AND :max";
$statement = $dbh->prepare($statement);
$statement->bindParam(':offset', $offset, PDO::PARAM_INT);
$statement->bindParam(':max', $max, PDO::PARAM_INT);
并且只要我不包含代码行:
$statement .= " AND RowNum BETWEEN :offset AND :max";
它工作正常但给我所有数据。
当包含该行时,我收到以下错误: -
捕获异常' PDOException' with message' SQLSTATE [42S22]:找不到列:207 [Microsoft] [SQL Server Native Client 11.0] [SQL Server]列名称无效' RowNum'。 (SQLExecute [207]在ext \ pdo_odbc \ odbc_stmt.c:254)'在C:\ pub \ test \ Classes \ Core.php:44
我很茫然,MSSQL对我来说是新手。
非常感谢。
答案 0 :(得分:1)
该列的谓词不能在WHERE子句中。 (访问行时,将评估WHERE子句中的谓词;在访问行之前,该表达式(分析函数)的值才可用。
您可以在HAVING子句中引用列别名:
" HAVING RowNum BETWEEN ... ";
答案 1 :(得分:1)
您不能在WHERE子句中使用COLUMN ALIAS(在您的情况下为RowNum
)。而是使用派生表更改您的查询,如下所示
SELECT * FROM
(
SELECT ROW_NUMBER() OVER (ORDER BY USERS.name DESC) AS RowNum,
CASE.no,
CASE.type,
CASE.date,
CASE.ju,
USERS.name,
TBRLMF.rd_rl_description
FROM dbo.CASE
INNER JOIN dbo.USERS
ON dbo.CASE.no = dbo.USERS.case_no
INNER JOIN dbo.CMSTBRLMF
ON dbo.USERS.relationship = dbo.TBRLMF.code
WHERE USERS.name LIKE '%string%'
AND USERS.no LIKE '%string%'
) X
WHERE RowNum BETWEEN 1 AND 10;
修改强>
您也可以使用CTE(公用表格表达式)来解决此问题,如下所示
创建CTE
WITH NEWCTE AS
(
SELECT ROW_NUMBER() OVER (ORDER BY USERS.name DESC) AS RowNum,
CASE.no,
CASE.type,
CASE.date,
CASE.ju,
USERS.name,
TBRLMF.rd_rl_description
FROM dbo.CASE
INNER JOIN dbo.USERS
ON dbo.CASE.no = dbo.USERS.case_no
INNER JOIN dbo.CMSTBRLMF
ON dbo.USERS.relationship = dbo.TBRLMF.code
WHERE USERS.name LIKE '%searchstring%'
AND USERS.no LIKE '%searchstring%'
)
查询CTE
SELECT *
FROM NEWCTE
WHERE RowNum BETWEEN 1 AND 10