Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Other SQL Server 2008 Topics
 Set Null Value To DataTable Column

Author  Topic 

Ravdeep
Starting Member

1 Post

Posted - 2011-12-30 : 13:08:59
Hi,

I have a dataset that has a null value in first column.What i am doing is fetching records from one table and inserting into another.I am writing the code.The problm is when i assing null value to datacolumn,it gives cast mismatch error which i know should be given.My question is whether there is any way to set the datacolumn to null directly.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString);

cmd.Connection = con;
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "getvalue";
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
cmd.Dispose();
con.Close();
con1.Open();
cmd1.Connection = con1;
cmd1.CommandType = CommandType.Text;
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
if (ds.Tables[0].Rows[i].IsNull("id"))
{
SqlInt32 x = SqlInt32.Null;
//SqlParameter p = new SqlParameter();
p.DbType = DbType.Int32;
p.Value = x;
ds.Tables[0].Rows[i]["id"] = p.Value;




cmd1.CommandText = "insert into testing values("+
ds.Tables[0].Rows[i]["id"] + ",'ravdeep')";
cmd1.ExecuteNonQuery();
}

}
}
}
Thanks,

Ravdeep

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2011-12-30 : 13:50:15
I didn't quite follow the logic you are trying to implement, but usually you can get around this problem using DBNull. When you want to send a null value in a parameter, set the parameter value to DBNull (and not null). When you want to test a column or parameter for null test it against DBNull.Value, for example:
if (x != DBNull.Value)
{
// do something here
}
Go to Top of Page
   

- Advertisement -