简体   繁体   English

如何将空值插入Uniqueidentifier列

[英]How to insert null values to a Uniqueidentifier Column

In my C# project I need to insert some null values to a UniqueIdentifier column. 在我的C#项目中,我需要向UniqueIdentifier列插入一些空值。

For fields city Guid, state Guid fields I should be able to insert null values if there is no value(uniqueidentifier) available. 对于字段城市Guid,状态Guid字段,如果没有可用的值(uniqueidentifier),我应该能够插入空值。 I am getting the following error 我收到以下错误

"Conversion failed when converting from a character string to uniqueidentifier." “从字符串转换为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);

You should not supply the values like this. 你不应该提供这样的值。 Create a SqlCommand and supply the values as parameters. 创建一个SqlCommand并将值作为参数提供。 To insert null values, use DBNull.Value 要插入空值,请使用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. 另一种方法是将NULL作为值提供。 See how do you insert null values into sql server 看看如何将空值插入sql server

You could also define a helper function to return either the value wrapped in quotes or a NULL string. 您还可以定义一个辅助函数,以返回包含在引号中的值或NULL字符串。

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

Then just supply GetQuotedParameterThing(tableGUID) to your command string. 然后只需将GetQuotedParameterThing(tableGUID)给您的命令字符串。

An answer already exists showing how to do this with ADO.NET parameters, which is a perfectly correct answer to this issue. 已经存在一个答案,显示如何使用ADO.NET参数执行此操作,这是对此问题的完美正确答案。 If you have to use raw TSQL, then you will need to distinguish between null / non-null values; 如果必须使用原始TSQL,则需要区分null / non-null值; the non-null values will require quotes, but the null values will need to be sent as null - no quotes. 非空值将需要引号,但空值将需要作为null发送 - 没有引号。 null is a perfectly valid nullable uniqueidentifier - but 'null' is not . null是一个完全有效的可空null uniqueidentifier - 但'null' 不是

However, in your example I suspect the real trick would be to change your sql.executeNonQuery method to accept parameters . 但是,在您的示例中,我怀疑真正的诀窍是更改您的sql.executeNonQuery方法以接受参数 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: 如果你只是简单地使你现有的executeNonQuery方法:

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 ; 只需添加对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. 上述更改可以在不影响任何现有代码的情况下进行 ,除非允许将来进行参数化。

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. 也许你可以检查string.Empty然后传入Guid.Empty或NULL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM