private void button1_Click(object sender, EventArgs e)
{
string rank = comboBox1.Text;
string cid = textBox16.Text;
string ConStr = "server=.;Data Source=LAPTOP-2SRQF5GA;Initial Catalog=JWXT;Integrated Security=True"; //连接字符串
SqlConnection conn = new SqlConnection(ConStr);
string sqlstr = "select S.NAME 学生姓名,C.NAME 课程名称,SC.SCORE 课程成绩," +
"case when SC.SCORE<60 then '不及格' " +
"when SC.SCORE>=60 and SC.SCORE<80 then '良好' " +
"when SC.SCORE>=80 and SC.SCORE<=100 then '优秀' " +
"end as 成绩等级 from S,C,SC " +
"where S.ID=SC.SID and C.ID=SC.CID";
string sqlstr1 = "select S.NAME 学生姓名,C.NAME 课程名称,SC.SCORE 课程成绩," +
"case when SC.SCORE<60 then '不及格' " +
"when SC.SCORE>=60 and SC.SCORE<80 then '良好' " +
"when SC.SCORE>=80 and SC.SCORE<=100 then '优秀' " +
"end as 成绩等级 from S,C,SC " +
"where S.ID=SC.SID and C.ID=SC.CID and C.ID='" + cid + "'";
string sqlstr2 = "if Object_Id('QA') is not null " +
"drop table QA" +
"select S.NAME 学生姓名, C.NAME 课程名称, SC.SCORE 课程成绩," +
"case when SC.SCORE < 60 then '不及格' when SC.SCORE >= 60 and SC.SCORE < 80 then '良好'" +
"when SC.SCORE >= 80 and SC.SCORE <= 100 then '优秀'" +
"end as 成绩等级" +
"into QA" +
"from S, C, SC" +
"where S.ID = SC.SID and C.ID = SC.CID" +
"select* from QA where 成绩等级 = '" + rank + "'";
string sqlstr3 = "if Object_Id('QA') is not null " +
"drop table QA" +
"select S.NAME 学生姓名, C.NAME 课程名称, SC.SCORE 课程成绩," +
"case when SC.SCORE < 60 then '不及格' when SC.SCORE >= 60 and SC.SCORE < 80 then '良好'" +
"when SC.SCORE >= 80 and SC.SCORE <= 100 then '优秀'" +
"end as 成绩等级" +
"into QA" +
"from S, C, SC" +
"where S.ID = SC.SID and C.ID = SC.CID and C.ID='" + cid + "'" +
"select* from QA where 成绩等级 = '" + rank + "'";
SqlDataAdapter sda = new SqlDataAdapter();
DataSet ds = new DataSet();
if (rank.Length == 0)
{
if (cid.Length == 0)
{
sda = new SqlDataAdapter(sqlstr, conn);
ds = new DataSet();
sda.Fill(ds);
this.dataGridView1.DataSource = ds.Tables[0];
MessageBox.Show("查询成功!");
}
else
{
sda = new SqlDataAdapter(sqlstr1, conn);
ds = new DataSet();
sda.Fill(ds);
this.dataGridView1.DataSource = ds.Tables[0];
MessageBox.Show("查询成功!");
}
}
else
{
if (cid.Length == 0)
{
sda = new SqlDataAdapter(sqlstr2, conn);
ds = new DataSet();
sda.Fill(ds);
this.dataGridView1.DataSource = ds.Tables[0];
MessageBox.Show("查询成功!");
}
else
{
sda = new SqlDataAdapter(sqlstr3, conn);
ds = new DataSet();
sda.Fill(ds);
this.dataGridView1.DataSource = ds.Tables[0];
MessageBox.Show("查询成功!");
}
}
}
你把代码中的
"if Object_Id('QA') is not null " +
"drop table QA"
这个东西去掉 你试试。应该就可以了
写sql时候,要注意关键字之间的空格,空格最好每行开头,好区分
string sqlstr2 = "if Object_Id('QA') is not null" +
" drop table QA" +
" select S.NAME 学生姓名, C.NAME 课程名称, SC.SCORE 课程成绩," +
" case when SC.SCORE < 60 then '不及格' when SC.SCORE >= 60 and SC.SCORE < 80 then '良好'" +
" when SC.SCORE >= 80 and SC.SCORE <= 100 then '优秀'" +
" end as 成绩等级" +
" into QA" +
" from S, C, SC" +
" where S.ID = SC.SID and C.ID = SC.CID" +
" select* from QA where 成绩等级 = '" + rank + "'";