6

这是要讨论的有点旧的内容,但我需要有人可以解释我如何在 SQL Server 中创建存储过程以从过程中返回值,例如:

SELECT NAME, ADDRESS 
FROM CUSTOMER 
WHERE IDCUSTOMER = 'DS212';

然后我需要它的客户名称和地址。

我需要将它作为一个存储过程,并告诉我如何在 VB.NET 上执行它。或许我们假设名称会提示为LABEL1.TEXT,地址会提示为LABEL2.TEXT。

我已经使用 return 改进了这个 SQL-Server 存储过程,但是在执行它之后我没有任何东西可以返回

CREATE PROCEDURE inserting_customer
            @custId varchar(10),
            @usr_id int
AS
BEGIN 
SET @usr_id = (SELECT MAX(SUBSTRING(CUSTOMER.idCustomer,3, LEN(CUSTOMER.IDCUSTOMER))) FROM CUSTOMER
WHERE 
SUBSTRING(CUSTOMER.idCustomer,1,2) = @custId)
END
RETURN @usr_id
GO

这是我的 VB.NET

  conn.Open()

        Dim cmd As New SqlCommand("inserting_customer", conn)

        Try
            cmd.CommandType = CommandType.StoredProcedure
            cmd.Parameters.Add("@custId", SqlDbType.VarChar)
            cmd.Parameters("@custId").Value = "YW"
            cmd.Parameters.Add("@usr_id", SqlDbType.Int)
            cmd.Parameters("@usr_id").Value = 0
            cmd.ExecuteNonQuery()
        Finally
            If cmd IsNot Nothing Then cmd.Dispose()
            If conn IsNot Nothing AndAlso conn.State <> ConnectionState.Closed Then conn.Close()
        End Try
4

1 回答 1

23

假设你在 sqlserver 中有这个 sproc

CREATE PROCEDURE GetNameAddress(@custID nvarchar(10))
as
BEGIN
SELECT NAME,ADDRESS FROM CUSTOMER WHERE IDCUSTOMER = @custID;
END

您调用它并以标准方式获得结果

' GetConnection is a method that creates and return the '
' SqlConnection used here according to your connection string'
Using cn = GetConnection()
   cn.Open()

   ' Create the command with the sproc name and add the parameter required'
   Dim cmd As SqlCommand = new SqlCommand("GetNameAddress", cn)
   cmd.CommandType = CommandType.StoredProcedure
   cmd.Parameters.AddWithValue("@custID", "DS212")

   ' Ask the command to create an SqlDataReader on the result of the sproc'
   Using r = cmd.ExecuteReader()

       ' If the SqlDataReader.Read returns true then there is a customer with that ID'
       if r.Read() then

           ' Get the first and second field frm the reader'
           lblName.Text = r.GetString(0)
           lblAddress.Text = r.GetString(1)
       end if
   End Using
End using

请注意,当您期望存储过程返回零或一条记录时,这是标准方法。如果您有多个记录,则在 SqlDataReader.Read 方法上使用 while 循环,并且您应该提供存储返回记录的控件。

于 2012-04-29T15:32:01.860 回答