2

In my C# project I need to insert some null values to a UniqueIdentifier column.

For fields city Guid, state Guid fields I should be able to insert null values if there is no value(uniqueidentifier) available. I am getting the following error

"Conversion failed when converting from a character string to uniqueidentifier."

here is my code.

   string Query = @"INSERT INTO mytable
                            (table_GUID,
                            Date,
                            city_GUID,
                            state_GUID,                            
                            ) 

                        VALUES
                        ('" + tableGUID + @"', 
                        '" + Date + @"',  
                        '" + cityGUID + @"',
                        '" + stateGUID + @"'
                    )                       

 string insert = sql.executeNonQuery(Query);
2

3 Answers 3

8

You should not supply the values like this. Create a SqlCommand and supply the values as parameters. To insert null values, use DBNull.Value

    var command = new SqlCommand(
        @"INSERT INTO mytable (table_GUID, Date, city_GUID, state_GUID)                      
          VALUES (@TableGuid, @Date, @CityGuid, @StateGuid)", sqlConnection);
    command.Parameters.AddWithValue("TableGuid", tableGUID ?? DBNull.Value);
    command.Parameters.AddWithValue("Date", Date);
    command.Parameters.AddWithValue("CityGuid", cityGUID ?? DBNull.Value);
    command.Parameters.AddWithValue("StateGuid", stateGUID ?? DBNull.Value);
    command.ExecuteNonQuery();

Another way to do this would be to supply NULL as a value. See how do you insert null values into sql server

You could also define a helper function to return either the value wrapped in quotes or a NULL string.

private string GetQuotedParameterThing(Guid? value)
{
    return value == null ? "NULL" : "\"+ value + \"";
}

Then just supply GetQuotedParameterThing(tableGUID) to your command string.

5
  • the problem is these are not always null. if there is no value then I should insert null. if there is a value then I should insert the Guid with single quotes. How can I insert null without single quotes in the above method? The single quotes are causing the issue here
    – Henry
    Jun 7, 2013 at 21:36
  • 1
    See my edit. You can use the null-coalescing operator to supply DBNull.Value if the parameter is null. Jun 7, 2013 at 21:41
  • thank you for your reply, But I I dont have access to sqlCommand. sqlCommand is in another class.Is it possible can you show your example in the format I am using? appreciate your help
    – Henry
    Jun 7, 2013 at 21:49
  • 2
    @Henry you should use SqlCommand, otherwise you are vulnerable to sql injection. Simply put, you are writing bad code. Don't do it. If you don't have access to it you need to gain access to it. Refactor the code. It's as simple as that. Jun 7, 2013 at 22:11
  • "then I should insert the Guid with single quotes" - no, you should not. uniqueidentifiers are not strings - thinking of them as strings is perhaps a large part of the problem here. Malvin is entirely correct to suggest passing them as ADO.NET parameters - and ADO.NET parameters can express null values via DBNull.Value Jun 7, 2013 at 22:31
1

An answer already exists showing how to do this with ADO.NET parameters, which is a perfectly correct answer to this issue. If you have to use raw TSQL, then you will need to distinguish between null / non-null values; the non-null values will require quotes, but the null values will need to be sent as null - no quotes. null is a perfectly valid nullable uniqueidentifier - but 'null' is not.

However, in your example I suspect the real trick would be to change your sql.executeNonQuery method to accept parameters. If you do not : then I guarantee you that your current system is fundamentally broken. Right now. It is dangerous. A problem. Risky.

But this is easily fixed; in your case, ridiculously easily; for example, this could be:

const string Query = @"
INSERT INTO mytable (table_GUID, Date, city_GUID, state_GUID) 
VALUES (@tableGUID, @Date, @cityGUID, @stateGUID)";

string insert = sql.executeNonQuery(
    Query, new { tableGUID, Date, cityGUID, stateGUID });
              ^^^ hot damn! who knew parameterization could be that easy!?

if you simply make your existing executeNonQuery method something like:

void executeNonQuery(string query, object args = null) {
    //... not shown: your code that gets a connection
    connection.Execute(query, args);
    //... not shown: your code that cleans up
}

by just adding a reference to dapper; simply, dapper makes correct parameterization a breeze; the above change could be made without impacting any of your existing code, except by allowing it to be parameterized in the future.

0

I think that the problem may have been that your code allowed "empty strings" to make it through. Maybe you could check for string.Empty and then pass in Guid.Empty or NULL instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.