简体   繁体   中英

How To Use Output Parameter In Stored Procedure In C#

First of all I did a lot of research on this topic but unfortunately I did not find what works for me. This is my stored procedure

USE [SIM]
GO
Create Proc [dbo].[AddPaymentTracking]

       @NPaymentRequest nvarchar(50),
       @DatePayment date,
       @id int out
AS
INSERT INTO [dbo].[PaymentTracking]
       ([NPaymentRequest]
       ,[DatePayment])

 VALUES
       (@NPaymentRequest, 
       @DatePayment)

Set @id=@@IDENTITY

and this is my c# class code

public async Task AddPaymentTracking(string NPaymentRequest, DateTime DatePayment)
    {
        DAL.DataAccessLayer DAL = new DAL.DataAccessLayer();
        await Task.Run(() => DAL.Open()).ConfigureAwait(false);
        SqlParameter[] param = new SqlParameter[3];

        param[0] = new SqlParameter("@NPaymentRequest", SqlDbType.NVarChar, 50)
        {
            Value = NPaymentRequest
        };

        param[1] = new SqlParameter("@DatePayment", SqlDbType.Date)
        {
            Value = DatePayment
        };

        param[2] = new SqlParameter("@id", SqlDbType.Int);
        param[2].Direction = ParameterDirection.Output;



        await Task.Run(() => DAL.ExcuteCommande("AddPaymentTracking", param)).ConfigureAwait(false);
        DAL.Close();

    }

and this is my c# form code

private async  void btnSave_Click(object sender, EventArgs e)
    {
     await supply.AddPaymentTracking(txtNPaymentRequest.Text, Convert.ToDateTime(txtDatePayment.EditValue, CultureInfo.CurrentCulture)).ConfigureAwait(true);  
     //int output = Get output Parameter
    }

How can I do it ?
Thanks in advance

You can get the out parameter value in your AddPaymentTracking method bu not in btnSave_Click unless you also expose it from your AddPaymentTracking method as an output (or ref) parameter.

    public async Task AddPaymentTracking(string NPaymentRequest, DateTime DatePayment, out int newRecordId)
    {
        . . .
        . . .

        await Task.Run(() => DAL.ExcuteCommande("AddPaymentTracking", param)).ConfigureAwait(false);

        newRecordId = (int)param[2].Value;
        DAL.Close();
    }

And this is how you would call the method with its new signature:

    private async void btnSave_Click(object sender, EventArgs e)
    {
        int output;
        await supply.AddPaymentTracking
        (
            txtNPaymentRequest.Text,
            Convert.ToDateTime(txtDatePayment.EditValue, CultureInfo.CurrentCulture), 
            out output
        ).ConfigureAwait(true);

        . . .
        . . .
    }

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