usausa / Smart-Net-Data-Accessor

2-way/outside SQL build-time data accessor generator library.
MIT License
24 stars 3 forks source link

How to excute Procedure in SQL Server? #7

Closed nShieldSolo closed 3 years ago

nShieldSolo commented 3 years ago

Hi Bro!

I want to execute a procedure was existed in Sql Server. How can I do it? please guide me.

Thanks for created good library and support.

usausa commented 3 years ago

Like this.

CREATE PROCEDURE TestProcedure
    @param1 INT,
    @param2 INT OUTPUT,
    @param3 INT OUTPUT
AS
BEGIN
    SELECT @param2 = @param2 + 1
    SELECT @param3 = @param1 + 1
    RETURN 100
END
public class TestProcedureParameter
{
    [Input]
    public int Param1 { get; set; }

    [InputOutput]
    public int Param2 { get; set; }

    [Output]
    public int Param3 { get; set; }

    [ReturnValue]
    public int Result { get; set; }
}
[DataAccessor]
public interface IExampleAccessor
{
    [Procedure("TestProcedure")]
    void CallTestProcedureByParameterClass(TestProcedureParameter parameter);

    [Procedure("TestProcedure")]
    int CallTestProcedureByArgument(int param1, ref int param2, out int param3);
}
public static void Main()
{
    var engine = new ExecuteEngineConfig()
        .ConfigureComponents(c =>
        {
            c.Add<IDbProvider>(new DelegateDbProvider(() => new SqlConnection(ConnectionString)));
        })
        .ToEngine();
    var factory = new DataAccessorFactory(engine);

    var accessor = factory.Create<IExampleAccessor>();

    // by argument
    var param2 = 2;
    var ret = accessor.CallTestProcedureByArgument(10, ref param2, out var param3);
    Debug.Assert(param2 == 3);
    Debug.Assert(param3 == 11);
    Debug.Assert(ret == 100);

    // by parameter class
    var parameter = new TestProcedureParameter { Param1 = 10, Param2 = 2 };
    accessor.CallTestProcedureByParameterClass(parameter);
    Debug.Assert(parameter.Param2 == 3);
    Debug.Assert(parameter.Param3 == 11);
    Debug.Assert(parameter.Result == 100);
}