You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用SqlDataAdapter执行查询时@parameterName附近出现语法错误求助

问题解决:@take附近语法错误

错误原因

SQL Server 中 TOP 关键字后不能直接跟参数变量,必须将参数放在括号内,也就是写成 TOP (@take) 才符合语法规范。

修正后的代码

con.Open();
string sql = "select top (@take) * from"+
"(Select ProductName, CategoryName, CompanyName, UnitPrice, ROW_NUMBER() OVER(ORDER BY ProductId) AS ROW_NUM "+
"from Products as p inner join Categories as c on p.CategoryID = c.CategoryID "+
"inner join Suppliers as s on p.SupplierID = s.SupplierID "+
") as x "+
"where x.ROW_NUM > @skip ";
SqlDataAdapter adapter = new SqlDataAdapter(sql, con);

adapter.SelectCommand.Parameters.Add("@take", SqlDbType.Int).Value = 20;
adapter.SelectCommand.Parameters.Add("@skip", SqlDbType.Int).Value = 10;

DataTable dt = new DataTable();
adapter.Fill(dt);
repProducts.DataSource = dt;
repProducts.DataBind();
con.Close();

更推荐的分页写法(OFFSET/FETCH)

从SQL Server 2012开始,支持OFFSET ... FETCH NEXT的标准分页语法,比用ROW_NUMBER的写法更简洁:

con.Open();
string sql = "Select ProductName, CategoryName, CompanyName, UnitPrice "+
"from Products as p inner join Categories as c on p.CategoryID = c.CategoryID "+
"inner join Suppliers as s on p.SupplierID = s.SupplierID "+
"ORDER BY ProductId "+
"OFFSET @skip ROWS FETCH NEXT @take ROWS ONLY";

SqlDataAdapter adapter = new SqlDataAdapter(sql, con);
adapter.SelectCommand.Parameters.Add("@take", SqlDbType.Int).Value = 20;
adapter.SelectCommand.Parameters.Add("@skip", SqlDbType.Int).Value = 10;

DataTable dt = new DataTable();
adapter.Fill(dt);
repProducts.DataSource = dt;
repProducts.DataBind();
con.Close();

内容的提问来源于stack exchange,提问作者user1238784

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 02:15:48