SQL Server存储过程期望参数

时间:2019-03-15 03:32:18

标签: sql-server vb.net stored-procedures

为什么我不断收到此错误:

  

System.Data.SqlClient.SqlException:'过程或函数'getTicket'需要未提供的参数'@project_id'。'

我已经创建了过程:

ALTER PROCEDURE [dbo].[getTicket]
    @project_id INT
AS
BEGIN
    SELECT 
        ticket_id, 
        ticket_name, 
        ticket_description, 
        ticket_url, 
        ticket_date_posted, 
        ticket_status 
    FROM 
        ticket 
    WHERE 
        project_id = @project_id
END

这是我的vb代码:

Dim sqlCom As SqlCommand = New SqlCommand
sqlCom.Connection = SQLcon
sqlCom.CommandType = CommandType.StoredProcedure
sqlCom.CommandText = "getTicket"

sqlCom.Parameters.AddWithValue("@project_id", Request.QueryString("id"))

SQLcon.Open()

Dim DS As New DataSet
Dim SQLDA As SqlDataAdapter = New SqlDataAdapter(sqlCom.CommandText, SQLcon)
SQLDA.SelectCommand.CommandTimeout = 120

SQLDA.Fill(DS, "gvTable")
GridView1.DataSource = DS
GridView1.DataBind()

SQLcon.Close()

2 个答案:

答案 0 :(得分:2)

这是错误的:

Dim SQLDA As SqlDataAdapter = New SqlDataAdapter(sqlCom.CommandText, SQLcon)

应该是这样:

Dim SQLDA As SqlDataAdapter = New SqlDataAdapter(sqlCom)

问题在于您正在创建一个SqlCommand对象并将参数添加到其中,但是随后您创建了一个不使用该命令的SqlDataAdapter。相反,您仅将SQL代码作为String传递给构造函数,因此数据适配器使用该代码创建一个新的SqlCommand对象。当然,该新命令没有添加参数。

您代码的其他方面也不太理想。这是我认为的两个明智选择:

Dim sqlCom As SqlCommand = New SqlCommand("getTicket", SQLcon) With {.CommandType = CommandType.StoredProcedure,
                                                                     .CommandTimeout = 120}

sqlCom.Parameters.AddWithValue("@project_id", Request.QueryString("id"))

Dim SQLDA As SqlDataAdapter = New SqlDataAdapter(sqlCom)

和:

Dim SQLDA As SqlDataAdapter = New SqlDataAdapter("getTicket", SQLcon)

With SQLDA.SelectCommand
    .CommandType = CommandType.StoredProcedure
    .CommandTimeout = 120
    .Parameters.AddWithValue("@project_id", Request.QueryString("id"))
End With

即使如此,这也忽略了以下事实:应避免使用AddWithValue属性的显式设置Add,而Value应当使用,例如

.Parameters.Add("@project_id", SqlDbType.Int).Value = Request.QueryString("id"))

答案 1 :(得分:0)

很多情况下,两个传递参数。

sqlCom.Parameters.AddWithValue("@project_id", SqlDbType.Int,Convert.toInt32(Request.QueryString("id")))

OR

sqlCom.Parameters.Add("@project_id", SqlDbType.Int);
sqlCom.Parameters("@project_id").Value = Convert.toInt32(Request.QueryString("id"));