这是一个有点陈旧的内容,需要讨论,但是我需要一个可以向我解释如何在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
假设您在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循环,并且应该提供控件来存储返回的记录。