Solved

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

Posted on 2012-12-31
13
4,288 Views
Last Modified: 2013-01-02
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
0
Comment
Question by:SSschultz
  • 8
  • 5
13 Comments
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 38732926
Assign DBNull.Value to the parameter you are inserting.

e.g.

SqlCommand cmd = ...

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

Open in new window

0
 

Author Comment

by:SSschultz
ID: 38732952
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.
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 38733039
Can you post that bit of logic so that I (we) can see what you are working with?
0
Migrating Your Company's PCs

To keep pace with competitors, businesses must keep employees productive, and that means providing them with the latest technology. This document provides the tips and tricks you need to help you migrate an outdated PC fleet to new desktops, laptops, and tablets.

 

Author Comment

by:SSschultz
ID: 38733055
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.
0
 

Author Comment

by:SSschultz
ID: 38733067
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
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 38733296
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.
0
 

Author Comment

by:SSschultz
ID: 38733322
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()
0
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
ID: 38733421
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

0
 

Author Comment

by:SSschultz
ID: 38733535
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.
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 38733604
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

0
 

Author Comment

by:SSschultz
ID: 38733655
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.
0
 

Author Comment

by:SSschultz
ID: 38737108
kaufmed,
Thanks much.. it works great. thanks again for your help and explaining the issue clearly.
Closing question with your solution.
0
 

Author Closing Comment

by:SSschultz
ID: 38737112
Thanks for excellent solution and explanation
0

Featured Post

Migrating Your Company's PCs

To keep pace with competitors, businesses must keep employees productive, and that means providing them with the latest technology. This document provides the tips and tricks you need to help you migrate an outdated PC fleet to new desktops, laptops, and tablets.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question