assign null value to string in C# and insert SQL Server decimal column that accepts null values

SSschultz
SSschultz used Ask the Experts™
on
Hi,
Need some help. This apparently is difficult to do.
I've tried many things which do not work

I'll outlline what I've tried so you don't list it as possible solution.

PROBLEM:  I'm trying to assign a null value to a string in C# that already has a value (the reason is for certain conditions to force real NULL value)
                    Then insert into SQL Server into a column that is decimal format (6,2) and accepts nulls.

 When I assign string to = "0" it sends to SQL table but I want actual NULL value to show up. And I've tried "NULL" and that doesn't work because it thinks it's a varchar into numeric(decimal).  It's important that the sQL column stays decimal because most of data is decimal format and works, but some cases I need to force an actual NULL value into SQL column. Have tried many suggestions on interent and nothing seems to work.

Thanks
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
ǩa̹̼͍̓̂ͪͤͭ̓u͈̳̟͕̬ͩ͂̌͌̾̀ͪf̭̤͉̅̋͛͂̓͛̈m̩̘̱̃e͙̳͊̑̂ͦ̌ͯ̚d͋̋ͧ̑ͯ͛̉Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015

Commented:
Assign DBNull.Value to the parameter you are inserting.

e.g.

SqlCommand cmd = ...

cmd.Parameters.AddWithValue("@theParam", DBNull.Value);

Open in new window

Author

Commented:
thanks for response.

Is there a way to do it above the insert sql command line? because the majority of the data is in decimal format and inserts correctly.

I tried your suggestion and still get error on the cmd insert exception line as "error in converting varchar to numeric.
ǩa̹̼͍̓̂ͪͤͭ̓u͈̳̟͕̬ͩ͂̌͌̾̀ͪf̭̤͉̅̋͛͂̓͛̈m̩̘̱̃e͙̳͊̑̂ͦ̌ͯ̚d͋̋ͧ̑ͯ͛̉Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015

Commented:
Can you post that bit of logic so that I (we) can see what you are working with?
How to Generate Services Revenue the Easiest Way

This Tuesday! Learn key insights about modern cyber protection services & gain practical strategies to skyrocket business:

- What it takes to build a cloud service portfolio
- How to determine which services will help your unique business grow
- Various use-cases and examples

Author

Commented:
string x;
x= "123";

if(x=="Nothing") {x=null;}

later in C#

cmd... insert the string x

Is it possible that something is wrong in SQL server 2005?
I have it set for decimal(6,2) and accepts Nulls.

The program works when the string is "4.43" and it inserts correctly into decimal(6,2) column in SQL server 2005.

Author

Commented:
when I change
 if(x=="Nothing") {x="0";}

it will insert the 0 into SQL server when the sting ="Nothing"
problem is setting the x to null and getting it to accept the insert into SQL as Null
ǩa̹̼͍̓̂ͪͤͭ̓u͈̳̟͕̬ͩ͂̌͌̾̀ͪf̭̤͉̅̋͛͂̓͛̈m̩̘̱̃e͙̳͊̑̂ͦ̌ͯ̚d͋̋ͧ̑ͯ͛̉Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015

Commented:
I'm sorry, I meant can you post the part where you are interacting with the database. The connection string is unimportant; just the part dealing with the SqlCommand object (along with the query and any parameters) is what I was hoping to see.

Author

Commented:
SqlConnection conn = new SqlConnection(connectionString);
string mySQLstring = "INSERT INTO [Table1] (Col1,Col2)values " +
"(" + "'" +stringTEST1 +"'" +"," + "'"+ stringTEST2 + "'" + ");";

try{ SqlCommand cmd = new SqlCommand(mySQLstring,conn);
        cmd.ExecuteNonQuery();
}
catch (Exception ex)
{streamwriter to capture exception here}
conn.Close()
Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015
Commented:
OK, I was afraid you were doing string concatenation. You certainly can continue with this approach, but it's a bit easier to read and work with (not to mention safer) if you use parameterized queries. Try this:

SqlConnection conn = new SqlConnection(connectionString);
string mySQLstring = "INSERT INTO [Table1] (Col1,Col2) VALUES (@col1Param, @col2Param)";

try
{
    SqlCommand cmd = new SqlCommand(mySQLstring,conn);
    
    cmd.Parameters.AddWithValue("@col1Param", DBNull.Value);
    cmd.Parameters.AddWithValue("@col2Param", 0.00);

    cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
    streamwriter to capture exception here
}

conn.Close()

Open in new window


One benefit of this approach is that you can let the framework worry about how to format strings and numbers to fit the query. You will notice that I don't have any quotes around either parameter within the query. If you were to pass a number (in the AddWithValue call), it will be filled in properly; likewise, if you were to pass a string, then it would be quoted properly when it arrives at the DB.

Note:  I put in some placeholder data above to demonstrate using DBNull.Value. Change these accordingly. If you want to send a numeric value, and that value starts off as string, then you will need to cast it to a numeric type before assigning it to the parameter.

e.g.

...
    cmd.Parameters.AddWithValue("@col2Param", Convert.ToInt32(stringTEST2));
...

Open in new window

Author

Commented:
Ok, thanks..
Do you have idea how to do it with current string concatenation method i'm using?
I'll try the parameters as you have shown.. I seem to remember where was a reason why I had to use string concatenation, but I will try your idea.

But if you have quick idea on how to pass null for string concatenation in meantime that would be great.  It will take me couple hours to get back to this to test out.
thanks for your help.
ǩa̹̼͍̓̂ͪͤͭ̓u͈̳̟͕̬ͩ͂̌͌̾̀ͪf̭̤͉̅̋͛͂̓͛̈m̩̘̱̃e͙̳͊̑̂ͦ̌ͯ̚d͋̋ͧ̑ͯ͛̉Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015

Commented:
To do it with string concatenation , you will have to use the word NULL, but make sure that there are no quotes around it.

e.g.

string example1 = "NULL";
string query1 = "INSERT INTO [table] VALUES (" + example1 + ")";  // there are no single quotes around the value here

string example2 = "hello world!";
string query2 = "INSERT INTO [table] VALUES ('" + example2 + "')";  // there are single quotes around the value here because you are passing an actual value, and not NULL

string this_is_the_string_null = "'NULL'";  // single quotes inside of double-quotes
string this_is_DB_null = "NULL";  // double quotes only

Open in new window

Author

Commented:
Oh fudge...  so the insert statement would have to know whether it was null or not in order for the correct formating with or without " "...?  (I have many variable per insert line)  
I now get your point about @parameters.  And will switch to see if I can get that to work.

I will end awarding points to you.. I want to test and get it to work and may have couple of quick followup ?'s.

thanks. I'll send more if I'm stuck with parameters or award points and close if I can get right away.

Author

Commented:
kaufmed,
Thanks much.. it works great. thanks again for your help and explaining the issue clearly.
Closing question with your solution.

Author

Commented:
Thanks for excellent solution and explanation

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial