2014年2月7日 星期五

[C#] Null value in SqlParameter

If you assign a null value to a SqlParameter object, it will cause an Error.
So the correct way is using DBNull.Value

For example,

sqlObj.SqlParams = new SqlParameter[]{
                    new SqlParameter("@TRANS_AMT", transLog.TransAmt),
                    new SqlParameter("@LEFT_BAL", transLog.LeftBal),
                    new SqlParameter("@LOG_TIME", transLog.LogTime)
                };
foreach(SqlParameter pa in sqlObj.SqlParams)
{
if(pa.Value==null)
{
   pa.Value =
DBNull.Value;
}
}


When executing the sql query, the column in Database will be a NULL value when it’s assigned as DBNull.Value.

Reference
How to assign null to a sqlparameter?

沒有留言:

張貼留言