简体   繁体   中英

Returning values from a SQL Server stored procedure?

I want to know whether there is any way besides the OUT parameter to get data from stored procedure into C# code.

Today my colleague told me that all select queries and the OUT parameters in a stored procedure are returned to the C# code. Is this correct? If yes, then how do I choose which results should be returned?

Is the answer same in case of VB6 code instead of c#?

Yes you can return values back to your application from a SP using either OUT parameters or a SELECT within the SP.

The OUT parameters are generally used for single values. The SELECT can be used for returning rows of results. A combination of both can be used in many different variations, such as the SP will return rows and a status OUT parameter can indicate row count or existence of the requested data.

CREATE PROC usp_MySpecialSP
  @conditionValue INT, @SPStatus INT OUT
AS
  IF EXISTS(SELECT * FROM TableName WHERE column1=conditionValue)
  BEGIN
    SELECT @SPStatus=COUNT(*) FROM TableName WHERE column1=conditionValue
    SELECT Column2, Column3, Column4 FROM TableName WHERE column1=conditionValue
  END
  ELSE
  BEGIN
    SELECT @SPStatus=0
  END
GO

Here you can pickup values if the m_SPStatusReturned>0 .

Check out below MSDN article how to pick up returned rows from SP http://msdn.microsoft.com/en-us/library/d7125bke.aspx

or a single value using SELECT http://msdn.microsoft.com/en-us/library/37hwc7kt.aspx

Yes it is correct - and the way you handle this is:

  • to get an OUT parameter, you need define a SqlParameter on your SqlCommand with ParameterDirection.Output

  • to get the result set of the SELECT in a stored procedure, you need to use a SqlDataReader or a SqlDataAdapter to get the results (as if you execute an inline SQL SELECT query)

  • and there's actually a third way : the RETURN keyword inside a stored procedure - typically used to return a numeric status value. You can capture that by using a SqlParameter with a value of ParameterDirection.ReturnValue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM