日期:2014-05-17  浏览次数:20543 次

在sql中读取某一列值,如果为空则把textbox中的值写入这一列
  cn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["cn"]);
        cn.Open();
        SqlCommand cmd = new SqlCommand("select (*)from book where booktime='" + TextBox1.Text  + "'", cn);


            if (booktime.Equals(DBNull.Value))
        {
            cn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["cn"]);
            cn.Open();
            SqlCommand cmd1 = new SqlCommand("insert into book(booktime)values('" + TextBox1.Text.Replace("'", "''") + "',)", cn);
            cmd.ExecuteNonQuery();


        }
问题是取出来的值需要进行声明才能在if语句中使用,但是如果取到的是空值该如何声明呢,目的是如果取到的是空值就把TextBox1的值写入这一列

------解决方案--------------------
你可以在代码中写存储过程。
例如:string sql=@"
                   declare @booktime string
                   select @booktime=booktime from book where 条件
                   if(@booktime=='')
                     begin
                     insert into book(booktime) values('{0}')
                     end";
然后,sql=string.format(sql," +TextBox1.Text.tostring()+ ");
最后,执行入库操作。试试看,惊喜等着你!