Question

Hi I'm still new in TSQL. How can I output Scalar variables so that my vb code can access it?

in VB I use the rs method. In this case I will have to create 3 rs to be be able to access the data below. I would like to have a stored proc that can give me the 4 values I need without using multiple rs.

Create PROCEDURE [dbo].[sp_tblTransaction_GET_All_Totals]

@TransID bigint

AS

Declare @MyTotalCharges as money 
Declare @MyTotalDiscounts as money 
Declare @MyTotalPayments as money 

Declare @TotalCharges as money
Declare @TotalDiscounts as money
Declare @TotalPayments as money
Declare @Balance as money

SELECT     @MyTotalCharges = SUM(Amount) 
FROM         tblTransactionDetails
WHERE     (TransID = @TransID)


SELECT     @MyTotalDiscounts = SUM(Amount) 
FROM         tblTransaction_DP
WHERE     (TransID = @TransID)

SELECT     @MyTotalPayments = SUM(Amount)
FROM         tblPayments
WHERE     (TransID = @TransID)

--Below are the scalar values I need to be ouputed and accessed by my vb app.
--How can I output the values below?

@TotalCharges = @MyTotalCharges
@TotalDiscounts = @MyTotalDiscounts
@TotalPayments = @MyTotalPayments
@Balance = (@MyTotalCharges - @MyTotalDiscounts - @MyTotalPayments)
Was it helpful?

Solution

You need to return the values from the stored procedure as a table. Add this to your procedure.

SELECT
    @TotalCharges as [Total Charges],
    @TotalDiscounts as [Total Discounts],
    @TotalPayments as [TotalPayments],
    @Balance as [Balance]

Then you can execute the stored procedure from your VB app and load the table into a DataTable.

int transactionID = 0;
DataTable table = new DataTable();

using (var connection = new SqlConnection("connectionString")
using (var command = new SqlCommand("sp_tblTransaction_GET_All_Totals", connection)
{
    connection.Open();
    command.CommandType = CommandType.StoredProcedure;
    command.Parameters.AddWithValue("@TransID", transactionID);

    using (var adapter = new SqlDataAdapter(command))
    {
        adapter.Fill(table);
    }   
}

calling a stored procedure from C# using SqlDataAdapter

Here's the documentation on SqlDataAdapter, which will include examples in both C# and VB.

MSDN - SqlDataAdapter Class (System.Data.SqlClient)

OTHER TIPS

Have you tried?

SELECT @Balance AS 'Balance', @TotalCharges AS 'TotalCharges' ... 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top