开发者

How to find if a value is NULL in SQL Server using c#

开发者 https://www.devze.com 2022-12-16 04:25 出处:网络
I would like to know which values are null in datatable in c# that is returned from ExecuteDataTable of SqlHelper class.

I would like to know which values are null in datatable in c# that is returned from ExecuteDataTable of SqlHelper class.

string select = "select * from testTable";
string val="";

DataTable  dt=dbcon.ExecuteDataTable(select);
foreach (DataRow dr in dt.Rows)
{
   foreach (DataColumn  dc in 开发者_如何学运维dt.Columns )
   {
       if(dr[dc].Equals (null))
       {
          val ="null";
       } 
       else  
       {
          val = dr[dc].ToString();
       }
   }
}

But unfortunately I didn't find any way to do it. Please let me know if there is a way. Thank you in advance.


You need DBNull.Value:

if (dr[dc] == DBNull.Value)


As well as David M's method, you can also use DataRow.IsNull:

if (dr.IsNull(dc))


if (dr[dc] == DBNull.Value) worked ! Here is why I needed it .It generates the insert script for given table name.

String tableName= "mytable";

           string select = "select * from "+tableName ;
           DataTable  dt=dbcon.ExecuteDataTable(select );
           StringBuilder sb = new StringBuilder();
           string pk="";

           sb.AppendFormat ( "select Name from sys.columns where Object_ID = Object_ID('{0}') and is_identity=1",tableName );
           try
           {
               pk = dbcon.ExecuteScalar(sb.ToString()).ToString();
           }
           catch
           { }
           sb.Remove(0, sb.Length);
            foreach (DataRow dr in dt.Rows  )
            {
                sb.Append("Insert INTO " + tableName + " VALUES( ");
                foreach (DataColumn  dc in dt.Columns )
                {
                    if (dc.ColumnName != pk)
                    {
                        string val = dr[dc].ToString();

                        if (dr[dc] == DBNull.Value)
                        {
                            sb.AppendFormat("{0} , ", "null");
                        }
                        else
                        {
                            sb.AppendFormat("'{0}' , ", dr[dc].ToString());
                        }
                    }
                }
                sb.Remove(sb.Length - 2, 2);
                sb.AppendLine(")");
            }
0

精彩评论

暂无评论...
验证码 换一张
取 消