使用SQL Server Management Studio进行数据库查询时遇到问题

时间:2015-09-11 16:38:34

标签: c# asp.net sql-server

当我查询我的一些数据时,我完全陷入了编程,

我想对我的数据库学生进行排序,以便按年在SQL Server中按年顺序排列:

select *   
from Student 
where year >=1 and year <= 4 
order by year;

代码似乎有效,但是当我在后面的aspx.cs代码中查询我的数据时,程序会发出错误警告我。

这是我的样本背后的aspx代码:

string yearfrom = (this.YearFrom.Value);
string yearto = (this.YearTo.Value);

if(yearfrom != "yearfrom1" && yearto != "yearto2")
{
   query = "select * from student where year >= '" + yearfrom + "' and year <= '" + yearto + "order by year'";
}

我在这里使用的查询似乎不起作用,我不知道为什么。

1 个答案:

答案 0 :(得分:0)

我已经找到了解决方案@Steve的答案也是正确的。

if(yearfrom != "yearfrom1" && yearto != "yearto2")
{
   query = @"select * from student 
             where [year] >= @from and [year] <= @to 
             order by [year]";
}

这一个也适用于@DeepakPawar一分钟前发布。

query = "select * from student where year >= " + yearfrom + " and year <= " + yearto + " order by year";
谢谢你们帮助我。