子查询返回的值不止一个

qqaazzstc 2014-12-25 01:34:01
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没法进去 执行报错 错误提示子查询返回的值不止一个
求高手赐教!
...全文
588 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
ajaxfeifei 2014-12-25
  • 打赏
  • 举报
回复

        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");

        }
我叫小菜菜 2014-12-25
  • 打赏
  • 举报
回复
“执行报错 错误提示子查询返回的值不止一个” 处理办法有2种: 1.在数据表中保证子查询的唯一性,保证子查询的返回值只有一个。 2.在子查询的多个返回值中取一个,抛弃其他多余的返回值。 比如: set MedName = (select MedName from Medical where row_rumber=1) -----割线--------------- 顺便提一下,这段代码存在很多问题: 第一、一个SQL字符串中包含了太多的SQL语句,不具备原子性,很容易跪的哦! 第二、拼接字符串的形式存在SQL注入的可能性,建议改为参数化查询。
S314324153 2014-12-25
  • 打赏
  • 举报
回复
用top 1,max()这类保证唯一
於黾 2014-12-25
  • 打赏
  • 举报
回复
如果你的逻辑不能改成如上形式,你还是做个存储过程好了
於黾 2014-12-25
  • 打赏
  • 举报
回复
你必须在语法上保证子查询的唯一性,而不是只要能查出唯一一条记录就可以 比如select * from就不能作为子查询 必须使用类似select count(*),select sum(列1)这种形式

110,536

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧