从数据库查询年龄段, 年龄字段是出生日期:dateTimePicker日期,1982-11-25年龄分为3种:30以下, 30到50 50以上 用comboBox控件实现选择;查询到当前日期,减去30得到30岁以下的数据,查询的结果不对, 请教大虾们提供个正确的方法?DateTime CurrentTime = System.DateTime.Now;
string str = "select * from clinMater where 1=1 ";
//得到系统日期
string strYMD = CurrentTime.ToString("d");
if(comboBox1.Text.Trim() != "")
{
if (comboBox1.Text == "30以下")
{
DateTime dt = Convert.ToDateTime(strYMD);
//系统日期减去30年
dt = dt.AddYears(-30);
//查询
str += "and 年龄" + " < '" + "dt" + "'";
}
else if(comboBox1.Text == "30到50")
{
}
else if (comboBox1.Text == "50以上")
{
}
}
string str = "select * from clinMater where 1=1 ";
//得到系统日期
string strYMD = CurrentTime.ToString("d");
if(comboBox1.Text.Trim() != "")
{
if (comboBox1.Text == "30以下")
{
DateTime dt = Convert.ToDateTime(strYMD);
//系统日期减去30年
dt = dt.AddYears(-30);
//查询
str += "and 年龄" + " < '" + "dt" + "'";
}
else if(comboBox1.Text == "30到50")
{
}
else if (comboBox1.Text == "50以上")
{
}
}
DateTime CurrentTime = System.DateTime.Now;
string str = "select * from clinMater where 1=1 ";
//得到系统日期
string strYMD = CurrentTime.ToString("d");
if(comboBox1.Text.Trim() != "")
{
if (comboBox1.Text == "30以下")
{
str += "and DATEDIFF(year, 生日字段,getdate())<30 ";
}
else if(comboBox1.Text == "30到50")
{
str += "and DATEDIFF(year, 生日字段,getdate())>=30 and DATEDIFF(year, 生日字段,getdate())<=50 ";
}
else if (comboBox1.Text == "50以上")
{
str += "and DATEDIFF(year, 生日字段,getdate())>50 ";
}
}
str += "and 年龄<#" + dt + "#";
日期应该是加#号才对吧
应该是大于dt。这样想当前1982-11-25,减去30年是1952-11-25,所以大于1952-11-25这个日期的才是30岁以下的。
string str = "select * from clinMater where 1=1 ";
//得到系统日期
string strYMD = CurrentTime.ToString("d");
//得到系统日期
string strYMD = CurrentTime.ToString("d");
if (comboBox1.Text.Trim() != "")
{
if (comboBox1.Text == "30岁以下")
{
DateTime dt = Convert.ToDateTime(strYMD);
//系统日期减去30年
dt = dt.AddYears(-30);
//查询
str = "borndate" + " > '" + dt + "'";//去掉dt两边的双引号及加号
}
else if (comboBox1.Text == "30-50岁")
{
DateTime dt = Convert.ToDateTime(strYMD);
//系统日期减去30年
dt = dt.AddYears(-30);
//查询
str = "borndate" + " < '" + dt + "' and borndate > '"+dt.AddYears(-20)+"'";
}
else if (comboBox1.Text == "50岁以上")
{
DateTime dt = Convert.ToDateTime(strYMD);
//系统日期减去30年
dt = dt.AddYears(-50);
//查询
str = "borndate" + " < '" + dt + "'";
}
}
{
str += "and DATEDIFF(year, 年龄,getdate())<30 ";
}
就可