C# 将参数传递给存储过程时出错

C# 将参数传递给存储过程时出错,c#,stored-procedures,C#,Stored Procedures,我有一个简单的搜索代码 我的存储过程: CREATE PROCEDURE [dbo].[sptest] ( @model NVARCHAR (20) ) AS begin SELECT * from table where model = @model end 我的c代码: SqlCommand comm = new SqlCommand(); comm.CommandType = CommandType.StoredProcedure; comm.Connection = c

我有一个简单的搜索代码

我的存储过程:

CREATE PROCEDURE [dbo].[sptest]
(
    @model NVARCHAR (20)
)
AS
begin
    SELECT * from table where model = @model
end
我的c代码:

SqlCommand comm = new SqlCommand();
comm.CommandType = CommandType.StoredProcedure;
comm.Connection = con;
comm.CommandText = "sptest" ;
comm.Parameters.Add("@model", SqlDbType.Int).Value = textBox1.Text;
如果我删除这一行: 通信参数。Add@model,SqlDbType.Int.Value=textBox1.Text; 我的代码运行没有错误

但当我添加这一行时,visual studio显示一个错误:

过程sptest没有参数,并且提供了参数


我的错误在哪里?

您的存储过程需要一个NVARCHAR20参数,而您传递了一个INT。这就是问题所在。因此,我建议您更改传递给SqlDbType.NVarChar的参数的类型

您的代码:

 SqlCommand comm = new SqlCommand();
            comm.CommandType = CommandType.StoredProcedure;
            comm.Connection = con;
            comm.CommandText = "sptest" ;
            comm.Parameters.Add("@model", SqlDbType.Int).Value = textBox1.Text; 
...
编辑后:

 SqlCommand comm = new SqlCommand();
            comm.CommandType = CommandType.StoredProcedure;
            comm.Connection = con;
            comm.CommandText = "sptest" ;
            comm.Parameters.Add("@model", SqlDbType.NVarChar,20).Value = textBox1.Text; 
...
试试这个。

参考下面的代码

CREATE PROC SPTest
(
@model      NVARCHAR (20)
)
AS

    BEGIN

        SET NOCOUNT ON

        SELECT * FROM <<TABLE_NAME>> WHERE model = @model


    END
C代码

    SqlConnection con = new SqlConnection("<<ConnectionStringValue>>");
    con.Open();

    SqlCommand com = new SqlCommand();
    com.Connection = con;
    com.CommandType = CommandType.StoredProcedure;

    com.CommandText = "SPTest";
    com.Parameters.Add("@model", SqlDbType.NVarChar, 20).Value = "<Parameter Value>";

    SqlDataReader reader = com.ExecuteReader();

    Rest Of Code Goes Here
    ...
    ...
    ...

首先,将SqlDbType.Int更改为SqlDbType.NVarChar。其次,我在代码中没有看到任何名为allmovie的sp。存储的proc需要一个NVARCHA20参数,而您提供了一个int类型的参数,即您提供的字符串值。表中模型栏的真实类型是什么?谢谢,这是我的错误。但我的过程保存时没有此行:
    SqlConnection con = new SqlConnection("<<ConnectionStringValue>>");
    con.Open();

    SqlCommand com = new SqlCommand();
    com.Connection = con;
    com.CommandType = CommandType.StoredProcedure;

    com.CommandText = "SPTest";
    com.Parameters.Add("@model", SqlDbType.NVarChar, 20).Value = "<Parameter Value>";

    SqlDataReader reader = com.ExecuteReader();

    Rest Of Code Goes Here
    ...
    ...
    ...