private void button1_Click(object sender, EventArgs e)
{
string strCon = @"Data Source=.;Initial Catalog=MZYSGZZ;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False";
SqlConnection conn = new SqlConnection(strCon);
string sSQL = null;
sSQL = "insert into chufang(PatientID,MedID) values ('" + textBox1.Text + "','" + textBox2.Text + "');update chufang set MedName = (select MedName from Medical) where MedID = ('" + textBox2.Text + "'); update chufang set PatientName = (select PatientName from PatientInfo) where PatientID = ('" + textBox1.Text + "');update chufang set MedQuantity = ('" + textBox3.Text + "') where PatientID = ('" + textBox1.Text + "')";
SqlCommand cmd = new SqlCommand(sSQL, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
DataBinding2("select * from chufang");
}
PatientName能顺利写进去 可MedName没法进去 执行报错 错误提示子查询返回的值不止一个
求高手赐教!
------解决思路----------------------
你必须在语法上保证子查询的唯一性,而不是只要能查出唯一一条记录就可以
比如select * from就不能作为子查询
必须使用类似select count(*),select sum(列1)这种形式
------解决思路----------------------
如果你的逻辑不能改成如上形式,你还是做个存储过程好了
------解决思路----------------------
用top 1,max()这类保证唯一
------解决思路----------------------
“执行报错 错误提示子查询返回的值不止一个”
处理办法有2种:
1.在数据表中保证子查询的唯一性,保证子查询的返回值只有一个。
2.在子查询的多个返回值中取一个,抛弃其他多余的返回值。
比如: set MedName = (select MedName from Medical where row_rumber=1)
-----割线---------------
顺便提一下,这段代码存在很多问题:
第一、一个SQL字符串中包含了太多的SQL语句,不具备原子性,很容易跪的哦!
第二、拼接字符串的形式存在SQL注入的可能性,建议改为参数化查询。
------解决思路----------------------
private void button1_Click(object sender, EventArgs e)
{
string strCon = @"Data Source=.;Initial Catalog=MZYSGZZ;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False";
SqlConnection conn = new SqlConnection(strCon);
string sSQL = null;
sSQL = "insert into chufang(PatientID,MedID) values ('" + textBox1.Text + "','" + textBox2.Text + "');update chufang set MedName = (select top(1) MedName from Medical) where MedID = ('" + textBox2.Text + "'); update chufang set PatientName = (select top(1) PatientName from PatientInfo) where PatientID = ('" + textBox1.Text + "');update chufang set MedQuantity = ('" + textBox3.Text + "') where PatientID = ('" + textBox1.Text + "')";
SqlCommand cmd = new SqlCommand(sSQL, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
DataBinding2("select * from chufang");
}