【问题标题】:How to select output scalar values in sql server?如何在 sql server 中选择输出标量值?
【发布时间】:2013-02-02 02:09:49
【问题描述】:

您好,我还是 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)

【问题讨论】:

标签: sql-server tsql scalar


【解决方案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);
    }   
}

calling a stored procedure from C# using SqlDataAdapter

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

MSDN - SqlDataAdapter Class (System.Data.SqlClient)

【讨论】:

  • 不错!非常感谢@J Lo。这就是我需要的。完美。
【解决方案2】:

你试过了吗?

SELECT @Balance AS 'Balance', @TotalCharges AS 'TotalCharges' ... 

【讨论】:

    猜你喜欢
    • 2019-04-30
    • 1970-01-01
    • 2013-05-05
    • 1970-01-01
    • 2012-04-04
    • 2019-06-10
    • 2022-01-12
    • 2014-07-29
    • 1970-01-01
    相关资源
    最近更新 更多