如何将空值插入Uniqueidentifier列

Hen*_*nry 2 .net c#

在我的C#项目中,我需要向UniqueIdentifier列插入一些空值.

对于字段城市Guid,状态Guid字段,如果没有可用的值(uniqueidentifier),我应该能够插入空值.我收到以下错误

"从字符串转换为uniqueidentifier时转换失败."

这是我的代码.

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

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

 string insert = sql.executeNonQuery(Query);
Run Code Online (Sandbox Code Playgroud)

Mal*_*ger 7

你不应该提供这样的值.创建一个SqlCommand并将值作为参数提供.要插入空值,请使用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();
Run Code Online (Sandbox Code Playgroud)

另一种方法是将NULL作为值提供.看看如何将空值插入sql server

您还可以定义一个辅助函数,以返回包含在引号中的值或NULL字符串.

private string GetQuotedParameterThing(Guid? value)
{
    return value == null ? "NULL" : "\"+ value + \"";
}
Run Code Online (Sandbox Code Playgroud)

然后只提供GetQuotedParameterThing(tableGUID)您的命令字符串.

  • @Henry 你应该使用 `SqlCommand`,否则你很容易受到 sql 注入的影响。简而言之,您正在编写糟糕的代码。不要这样做。如果您无权访问它,则需要访问它。重构代码。就这么简单。 (2认同)