Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 添加SQL参数时使用null_C#_Sql Server 2008 - Fatal编程技术网

C# 添加SQL参数时使用null

C# 添加SQL参数时使用null,c#,sql-server-2008,C#,Sql Server 2008,我想在表中添加一些空值: command.CommandText = "INSERT into clients (Addres, companyID) VALUES (@Addres, @companyID) ; select SCOPE_IDENTITY();"; command.Parameters.AddWithValue("@Addres", null); command.Parameters.AddWithValue("@companyID", null); 表dessign允许空值

我想在表中添加一些空值:

command.CommandText =
"INSERT into clients (Addres, companyID) VALUES (@Addres, @companyID) ; select SCOPE_IDENTITY();";
command.Parameters.AddWithValue("@Addres", null);
command.Parameters.AddWithValue("@companyID", null);
表dessign允许空值。为什么我会有这个错误呢

The parameterized query '(@Addres nvarchar(4000),@companyID nvarchar(4000))INSERT into cl' expects the parameter '@Addres', which was not supplied.
改用

改用

对于SQL中的空值,必须使用DBNull类。您的代码如下所示:

command.Parameters.AddWithValue("@Addres", DBNull.Value);
command.Parameters.AddWithValue("@companyID", DBNull.Value);
对于SQL中的空值,必须使用DBNull类。您的代码如下所示:

command.Parameters.AddWithValue("@Addres", DBNull.Value);
command.Parameters.AddWithValue("@companyID", DBNull.Value);
你可以用

阅读:

Value可以用于任何类型,而不是

可以方便地使代码更具可读性和类型安全性,例如:

var addrVal = new System.Data.SqlTypes.SqlString(someAddress);
// ...
if (condition) addrVal = System.Data.SqlTypes.SqlString.Null;
command.Parameters.AddWithValue("@Addres", addrVal);
你可以用

阅读:

Value可以用于任何类型,而不是

可以方便地使代码更具可读性和类型安全性,例如:

var addrVal = new System.Data.SqlTypes.SqlString(someAddress);
// ...
if (condition) addrVal = System.Data.SqlTypes.SqlString.Null;
command.Parameters.AddWithValue("@Addres", addrVal);

文档链接:文档链接:如果参数不是字符串怎么办?@ThorstenDittmar:但在本例中它是一个字符串,两者都是nvarchar,这就是我使用它的原因。如果它是一个into,例如:SqlInt32.Null。这是类型安全的版本。我只想提到:-如果参数不是字符串怎么办?@ThorstenDittmar:但在本例中,它是字符串,两者都是nvarchar,这就是我使用它的原因。如果它是一个into,例如:SqlInt32.Null。这是类型安全版本。我只是想提到:-D