在我的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)
你不应该提供这样的值.创建一个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)您的命令字符串.