SQL Server存储过程并在VB.NET中执行

6 sql vb.net sql-server stored-procedures sql-server-2008

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

SELECT NAME, ADDRESS 
FROM CUSTOMER 
WHERE IDCUSTOMER = 'DS212';
Run Code Online (Sandbox Code Playgroud)

然后我需要其客户的名称和地址.

我需要将它作为存储过程,并告诉我如何在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
Run Code Online (Sandbox Code Playgroud)

这是我的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
Run Code Online (Sandbox Code Playgroud)

Ste*_*eve 22

假设你在sqlserver中有这个sproc

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

你打电话给它,并以标准方式得到结果

' 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
Run Code Online (Sandbox Code Playgroud)

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

  • 尊重这个答案!非常感谢您提供包含语法和明确说明的朋友!上帝保佑你...爱这个 (2认同)