我有这个参数化查询:
SELECT
ClientId, FirstName, LastName, AccNumber, AccBalance, Created
FROM
(SELECT
tbl.*,
ROW_NUMBER() OVER (ORDER BY @dbColumnOrder ASC) AS rownum
FROM [DB].[dbo].[MyTable] AS tbl
WHERE @dbColumnFilter IS NOT NULL) seq
WHERE
seq.rownum BETWEEN @iDisplayStart AND @iDisplayLength
我设置了这样的参数:
command.Parameters.Add(new SqlParameter("@dbColumnOrder", columns[iSortCol]));
command.Parameters.Add(new SqlParameter("@dbColumnFilter", "AccNumber"));
command.Parameters.Add(new SqlParameter("@iDisplayStart", iDisplayStart));
command.Parameters.Add(new SqlParameter("@iDisplayLength", (iDisplayLength + iDisplayStart)));
我调试了很多次,所以我确信我对new SqlParameter()
的第二个参数有正确的值。但是,当我得到结果时,好像WHERE @dbColumnFilter IS NOT NULL
根本没有被执行,我也认为ORDER BY @dbColumnOrder ASC
也被跳过了。如果我转到Ms SQL Server Management Studio
并通过用具体值替换参数来手动执行查询,如下所示:
SELECT
ClientId, FirstName, LastName, AccNumber, AccBalance, Created
FROM
(SELECT
tbl.*,
ROW_NUMBER() OVER (ORDER BY ClientId ASC) AS rownum
FROM [DB].[dbo].[MyTable] AS tbl
WHERE AccNumber IS NOT NULL) seq
WHERE
seq.rownum BETWEEN 0 AND 10
我得到了预期的结果。另外,我试图硬编码传递给数据库的值,如下所示:
command.Parameters.Add(new SqlParameter("@dbColumnOrder", "ClientId");
command.Parameters.Add(new SqlParameter("@dbColumnFilter", "AccNumber"));
command.Parameters.Add(new SqlParameter("@iDisplayStart", 0));
command.Parameters.Add(new SqlParameter("@iDisplayLength", 10));
但是数据库的结果仍然好像没有执行OrderBy
和IS NOT NULL
。