首页 > 解决方案 > C# 中的 SP 问题:需要未提供的参数“@Image”

问题描述

我遇到了一个问题,在现有的类似问题中找不到解决方案。问题是我有以下存储过程:

ALTER PROCEDURE SP_EditCustomer @ID int, @Name NVarchar(100), @Email Nvarchar(200), @Contact bigint, 
@Address NVarchar(350), @About NVarChar(350), @Image image = null
AS
if(@Image is null)
Begin
UPDATE clientTable
SET ClientName = @Name, Contact= @Contact, Address = @Address, About = @About, Email = @Email
                 WHERE ClientID = @ID;
End
Else
Begin
UPDATE clientTable
SET ClientName = @Name, Contact= @Contact, Address = @Address, About = @About, Email = @Email,
                 Photo = @Image
                 WHERE ClientID = @ID;
End

我已将@image参数设置为默认,但每当我在 C# winforms 中使用以下代码连接到 SQL Server 时:

// Inserting image into DB
byte[] img = null;
if (imgLoc != null && imgLoc != "")
{
    FileStream fs = new FileStream(imgLoc, FileMode.Open, FileAccess.Read);
    BinaryReader br = new BinaryReader(fs);
    img = br.ReadBytes((int)fs.Length);
}
else
{
    img = null;
}

    //Connecting to Database
    cmd = conString.CreateCommand();
    cmd.CommandText = "Exec SP_EditCustomer @ID, @Name, @Email, @Contact, @Address, @About, @Image";

    cmd.Parameters.Add("@ID", SqlDbType.Int).Value = Convert.ToInt32(txtEditByID.Text);
    cmd.Parameters.Add("@Name", SqlDbType.NVarChar, 100).Value = txtFullName.Text.ToString();
    cmd.Parameters.Add("@Email", SqlDbType.NVarChar, 200).Value = txtEmail.Text.ToString();
    cmd.Parameters.Add("@Contact", SqlDbType.BigInt).Value = txtContact.Text;
    cmd.Parameters.Add("@Address", SqlDbType.NVarChar, 350).Value = txtAddress.Text.ToString();
    cmd.Parameters.Add("@About", SqlDbType.NVarChar, 350).Value = txtAbout.Text.ToString();
    cmd.Parameters.Add("@Image", SqlDbType.Image).Value = img;

    conString.Open();
    cmd.ExecuteNonQuery();
    conString.Close();

我收到此错误:

参数化查询 '(@ID int,@Name nvarchar(100),@Email nvarchar(200),@Contact bigin' 需要未提供的参数 '@Image'。

尽管如果没有选择新图像,则现有图像不应更改(为此我传递了 null 但仍然出现上述错误)。

标签: c#sql-server

解决方案


感谢@DaleK 建议 DBNull.Value。

我已经通过添加以下几行的建议解决了这个问题:

 if(img!=null)
 cmd.Parameters.Add("@Image", SqlDbType.Image).Value = img;
 else
 cmd.Parameters.Add("@Image", SqlDbType.Image).Value = DBNull.Value;

推荐阅读