0

嗨,我还是 TSQL 的新手。如何输出标量变量以便我的 vb 代码可以访问它?

在 VB 中,我使用 rs 方法。在这种情况下,我必须创建 3 个 rs 才能访问下面的数据。我想要一个存储过程,它可以在不使用多个 rs 的情况下为我提供所需的 4 个值。

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)
4

2 回答 2

1

你有没有尝试过?

SELECT @Balance AS 'Balance', @TotalCharges AS 'TotalCharges' ... 
于 2013-02-17T16:21:58.750 回答
1

您需要将存储过程中的值作为表返回。将此添加到您的程序中。

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

然后,您可以从 VB 应用程序执行存储过程并将表加载到 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);
    }   
}

使用 SqlDataAdapter 从 C# 调用存储过程

这是有关 SqlDataAdapter 的文档,其中将包含 C# 和 VB 中的示例。

MSDN - SqlDataAdapter 类 (System.Data.SqlClient)

于 2013-02-17T16:29:17.310 回答