ADO.NET参数化查询未正确执行

时间:2014-07-30 10:45:30

标签: c# sql-server-2008 ado.net

我有这个参数化查询:

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));

但是数据库的结果仍然好像没有执行OrderByIS NOT NULL

0 个答案:

没有答案