当我尝试通过存储过程插入null值时,得到SqlException
本文关键字:值时 null 得到 SqlException 插入 存储过程 | 更新日期: 2023-09-27 18:29:20
我有一个表,它接受一组参数,并通过使用INSERT INTO语句的存储过程将其保存为新联系人。由于某种原因,当我的一些参数为空时,我会得到一个SqlException。SQL Server表中所有保留为null的参数实际上都可以为null,所以我不理解这个问题。我的想法是,我的INSERT语句接受所有参数,即使它们为空,并试图将它们插入到我的表中,我认为这是一个语法上的"no"
无论如何,这是C#代码:
try
{
using (SqlConnection sqlConn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("Insert_NewContact", sqlConn))
{
sqlConn.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@CompanyID", CompanyID);
cmd.Parameters.AddWithValue("@email", email);
cmd.Parameters.AddWithValue("@phone", phone);
cmd.Parameters.AddWithValue("@fax", fax);
cmd.Parameters.AddWithValue("@fName", fName);
cmd.Parameters.AddWithValue("@lName", lName);
cmd.Parameters.AddWithValue("@sendVia", sendVia);
cmd.Parameters.AddWithValue("@default", defaultContact);
cmd.Parameters.AddWithValue("@repo", repo);
cmd.Parameters.AddWithValue("@fail", fail);
cmd.Parameters.AddWithValue("@borrow", borrow);
cmd.Parameters.AddWithValue("@loan", loan);
cmd.ExecuteNonQuery();
sqlConn.Close();
}
}
}
catch (Exception e)
{
throw e;
}
这是SQL中的存储过程:
ALTER PROCEDURE [dbo].[Insert_NewContact]
@CompanyID INT,
@email VARCHAR(50),
@phone VARCHAR(50),
@fax VARCHAR(50),
@fName VARCHAR(50),
@lName VARCHAR(50),
@sendVia VARCHAR(50),
@default BIT,
@repo TINYINT,
@fail TINYINT,
@borrow TINYINT,
@loan TINYINT
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
INSERT INTO Master_Contacts(
companyID,
fName,
lName,
phone,
email,
fax,
send_via,
defaultcontact,
repoRole,
borrowRole,
failRole,
loanRole
)
VALUES (
@CompanyID,
@fName,
@lName,
@phone,
@email,
@fax,
@sendVia,
@default,
@repo,
@borrow,
@fail,
@loan
)
END TRY
不确定为什么AS BEGIN和NOCOUNT如此奇怪,但它们在存储过程中是正确的。
无论如何,如果我在应用程序中留下空的电子邮件、电话、传真等,我会收到以下错误:
用户代码未处理SqlException过程或函数"Insert_NewContact"需要参数"@email",但未提供该参数。
如何编辑我的存储过程以使其使用null值?
将参数的默认值设置为null,请尝试以下操作:
@CompanyID INT,
@email VARCHAR(50) = null,
@phone VARCHAR(50) = null,
@fax VARCHAR(50) = null,
@fName VARCHAR(50) = null,
@lName VARCHAR(50),
@sendVia VARCHAR(50),
@default BIT,
@repo TINYINT,
@fail TINYINT,
@borrow TINYINT,
@loan TINYINT
当您有空值时,应该传递DBNull.Value。例如
cmd.Parameters.AddWithValue("@email", email == null ? DBNull.Value : (object)email);
ALTER PROCEDURE [dbo].[Insert_NewContact]
@CompanyID INT,
@email VARCHAR(50) = null,
@phone VARCHAR(50) = null,
@fax VARCHAR(50) = null,
@fName VARCHAR(50) = null,
@lName VARCHAR(50) = null,
@sendVia VARCHAR(50) = null,
@default BIT = 0,
@repo TINYINT = 0,
@fail TINYINT = 0,
@borrow TINYINT = 0,
@loan TINYINT = 0
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
INSERT INTO Master_Contacts(
companyID,
fName,
lName,
phone,
email,
fax,
send_via,
defaultcontact,
repoRole,
borrowRole,
failRole,
loanRole
)
VALUES (
@CompanyID,
@fName,
@lName,
@phone,
@email,
@fax,
@sendVia,
@default,
@repo,
@borrow,
@fail,
@loan
)
END TRY