Calling SQL Defined function in C#











up vote
12
down vote

favorite
2












I have written this scalar function in TSQL:



create function TCupom (@cupom int)
returns float
as
begin
declare @Tcu float;

select @Tcu = sum (total) from alteraca2 where pedido = @cupom

if (@tcu is null)
set @tcu = 0;

return @tcu;
end


I want to call this function in my C# code. Here's what I have so far:



public void TotalCupom(int cupom)
{
float SAIDA;
SqlDataAdapter da2 = new SqlDataAdapter();

if (conex1.State == ConnectionState.Closed)
{
conex1.Open();
}

SqlCommand Totalf = new SqlCommand("Tcupom", conex1);
SqlParameter code1 = new SqlParameter("@code", SqlDbType.Int);
code1.Value = cupom ;
Totalf.CommandType = CommandType.StoredProcedure ;
SAIDA = Totalf.ExecuteScalar();

return SAIDA;
}









share|improve this question




















  • 1




    Are you having a problem? Would you like to tell us what it is?
    – SLaks
    Jun 11 '13 at 14:49










  • Possible duplicate of ExecuteScalar always returns null when calling a scalar-valued function
    – GSerg
    Aug 23 at 12:45















up vote
12
down vote

favorite
2












I have written this scalar function in TSQL:



create function TCupom (@cupom int)
returns float
as
begin
declare @Tcu float;

select @Tcu = sum (total) from alteraca2 where pedido = @cupom

if (@tcu is null)
set @tcu = 0;

return @tcu;
end


I want to call this function in my C# code. Here's what I have so far:



public void TotalCupom(int cupom)
{
float SAIDA;
SqlDataAdapter da2 = new SqlDataAdapter();

if (conex1.State == ConnectionState.Closed)
{
conex1.Open();
}

SqlCommand Totalf = new SqlCommand("Tcupom", conex1);
SqlParameter code1 = new SqlParameter("@code", SqlDbType.Int);
code1.Value = cupom ;
Totalf.CommandType = CommandType.StoredProcedure ;
SAIDA = Totalf.ExecuteScalar();

return SAIDA;
}









share|improve this question




















  • 1




    Are you having a problem? Would you like to tell us what it is?
    – SLaks
    Jun 11 '13 at 14:49










  • Possible duplicate of ExecuteScalar always returns null when calling a scalar-valued function
    – GSerg
    Aug 23 at 12:45













up vote
12
down vote

favorite
2









up vote
12
down vote

favorite
2






2





I have written this scalar function in TSQL:



create function TCupom (@cupom int)
returns float
as
begin
declare @Tcu float;

select @Tcu = sum (total) from alteraca2 where pedido = @cupom

if (@tcu is null)
set @tcu = 0;

return @tcu;
end


I want to call this function in my C# code. Here's what I have so far:



public void TotalCupom(int cupom)
{
float SAIDA;
SqlDataAdapter da2 = new SqlDataAdapter();

if (conex1.State == ConnectionState.Closed)
{
conex1.Open();
}

SqlCommand Totalf = new SqlCommand("Tcupom", conex1);
SqlParameter code1 = new SqlParameter("@code", SqlDbType.Int);
code1.Value = cupom ;
Totalf.CommandType = CommandType.StoredProcedure ;
SAIDA = Totalf.ExecuteScalar();

return SAIDA;
}









share|improve this question















I have written this scalar function in TSQL:



create function TCupom (@cupom int)
returns float
as
begin
declare @Tcu float;

select @Tcu = sum (total) from alteraca2 where pedido = @cupom

if (@tcu is null)
set @tcu = 0;

return @tcu;
end


I want to call this function in my C# code. Here's what I have so far:



public void TotalCupom(int cupom)
{
float SAIDA;
SqlDataAdapter da2 = new SqlDataAdapter();

if (conex1.State == ConnectionState.Closed)
{
conex1.Open();
}

SqlCommand Totalf = new SqlCommand("Tcupom", conex1);
SqlParameter code1 = new SqlParameter("@code", SqlDbType.Int);
code1.Value = cupom ;
Totalf.CommandType = CommandType.StoredProcedure ;
SAIDA = Totalf.ExecuteScalar();

return SAIDA;
}






c# sql visual-studio-2010 sql-server-2008






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 16 at 9:25









Massimiliano Kraus

2,33741532




2,33741532










asked Jun 11 '13 at 14:47









alejandro carnero

77061836




77061836








  • 1




    Are you having a problem? Would you like to tell us what it is?
    – SLaks
    Jun 11 '13 at 14:49










  • Possible duplicate of ExecuteScalar always returns null when calling a scalar-valued function
    – GSerg
    Aug 23 at 12:45














  • 1




    Are you having a problem? Would you like to tell us what it is?
    – SLaks
    Jun 11 '13 at 14:49










  • Possible duplicate of ExecuteScalar always returns null when calling a scalar-valued function
    – GSerg
    Aug 23 at 12:45








1




1




Are you having a problem? Would you like to tell us what it is?
– SLaks
Jun 11 '13 at 14:49




Are you having a problem? Would you like to tell us what it is?
– SLaks
Jun 11 '13 at 14:49












Possible duplicate of ExecuteScalar always returns null when calling a scalar-valued function
– GSerg
Aug 23 at 12:45




Possible duplicate of ExecuteScalar always returns null when calling a scalar-valued function
– GSerg
Aug 23 at 12:45












2 Answers
2






active

oldest

votes

















up vote
32
down vote



accepted










You can't just call the function name, you will need to write an inline SQL statement which makes use of the UDF:



SqlCommand Totalf = new SqlCommand("SELECT dbo.Tcupom(@code)", conex1);


And remove the CommandType, this isn't a Stored Procedure, its a User Defined Function.



In all:



public void TotalCupom(int cupom)
{
float SAIDA;
SqlDataAdapter da2 = new SqlDataAdapter();
if (conex1.State == ConnectionState.Closed)
{
conex1.Open();
}
SqlCommand Totalf = new SqlCommand("SELECT dbo.Tcupom(@code)", conex1);
SqlParameter code1 = new SqlParameter("@code", SqlDbType.Int);
code1.Value = cupom;
SAIDA = Totalf.ExecuteScalar();

return SAIDA;
}





share|improve this answer























  • Actually because he did Totalf.CommandType = CommandType.StoredProcedure he can just call the function name.
    – Scott Chamberlain
    Jun 11 '13 at 14:50












  • @ScottChamberlain Are you sure? What if there was a stored procedure called Tcupom? Surely SQL Server would get confused...
    – Curt
    Jun 11 '13 at 14:52








  • 2




    No, you are right, I just realized he was using a scalar function, not a table based function. I don't know if those can be called via SqlCommand set as StoredProcedure
    – Scott Chamberlain
    Jun 11 '13 at 14:53








  • 2




    Refresh your page, I agree with you now.
    – Scott Chamberlain
    Jun 11 '13 at 14:57






  • 1




    number of corrections: 1. your method has a void return type and, you are returning something else (return SAIDA;) 2. you have initialize an SqlDataAdapter and it is never used. 3. ExecuteScalar(); returns an object, needs type conversion.
    – Sam Saarian
    Dec 5 '17 at 22:18


















up vote
0
down vote













...

try
{
if (connectionState != ConnectionState.Open)
conn.Open();
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "udfName";
cmd.CommandType = CommandType.StoredProcedure;

foreach (var cmdParam in sqlParams)
{
cmd.Parameters.Add(cmdParam);
}


var retValParam = new SqlParameter("RetVal", SqlDbType.Int)
{
//Set this property as return value
Direction = ParameterDirection.ReturnValue
};

cmd.Parameters.Add(retValParam);
cmd.ExecuteScalar();

retVal = retValParam.Value;
}
}
finally
{
if (connectionState == ConnectionState.Open)
conn.Close();
}

...





share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f17047057%2fcalling-sql-defined-function-in-c-sharp%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    32
    down vote



    accepted










    You can't just call the function name, you will need to write an inline SQL statement which makes use of the UDF:



    SqlCommand Totalf = new SqlCommand("SELECT dbo.Tcupom(@code)", conex1);


    And remove the CommandType, this isn't a Stored Procedure, its a User Defined Function.



    In all:



    public void TotalCupom(int cupom)
    {
    float SAIDA;
    SqlDataAdapter da2 = new SqlDataAdapter();
    if (conex1.State == ConnectionState.Closed)
    {
    conex1.Open();
    }
    SqlCommand Totalf = new SqlCommand("SELECT dbo.Tcupom(@code)", conex1);
    SqlParameter code1 = new SqlParameter("@code", SqlDbType.Int);
    code1.Value = cupom;
    SAIDA = Totalf.ExecuteScalar();

    return SAIDA;
    }





    share|improve this answer























    • Actually because he did Totalf.CommandType = CommandType.StoredProcedure he can just call the function name.
      – Scott Chamberlain
      Jun 11 '13 at 14:50












    • @ScottChamberlain Are you sure? What if there was a stored procedure called Tcupom? Surely SQL Server would get confused...
      – Curt
      Jun 11 '13 at 14:52








    • 2




      No, you are right, I just realized he was using a scalar function, not a table based function. I don't know if those can be called via SqlCommand set as StoredProcedure
      – Scott Chamberlain
      Jun 11 '13 at 14:53








    • 2




      Refresh your page, I agree with you now.
      – Scott Chamberlain
      Jun 11 '13 at 14:57






    • 1




      number of corrections: 1. your method has a void return type and, you are returning something else (return SAIDA;) 2. you have initialize an SqlDataAdapter and it is never used. 3. ExecuteScalar(); returns an object, needs type conversion.
      – Sam Saarian
      Dec 5 '17 at 22:18















    up vote
    32
    down vote



    accepted










    You can't just call the function name, you will need to write an inline SQL statement which makes use of the UDF:



    SqlCommand Totalf = new SqlCommand("SELECT dbo.Tcupom(@code)", conex1);


    And remove the CommandType, this isn't a Stored Procedure, its a User Defined Function.



    In all:



    public void TotalCupom(int cupom)
    {
    float SAIDA;
    SqlDataAdapter da2 = new SqlDataAdapter();
    if (conex1.State == ConnectionState.Closed)
    {
    conex1.Open();
    }
    SqlCommand Totalf = new SqlCommand("SELECT dbo.Tcupom(@code)", conex1);
    SqlParameter code1 = new SqlParameter("@code", SqlDbType.Int);
    code1.Value = cupom;
    SAIDA = Totalf.ExecuteScalar();

    return SAIDA;
    }





    share|improve this answer























    • Actually because he did Totalf.CommandType = CommandType.StoredProcedure he can just call the function name.
      – Scott Chamberlain
      Jun 11 '13 at 14:50












    • @ScottChamberlain Are you sure? What if there was a stored procedure called Tcupom? Surely SQL Server would get confused...
      – Curt
      Jun 11 '13 at 14:52








    • 2




      No, you are right, I just realized he was using a scalar function, not a table based function. I don't know if those can be called via SqlCommand set as StoredProcedure
      – Scott Chamberlain
      Jun 11 '13 at 14:53








    • 2




      Refresh your page, I agree with you now.
      – Scott Chamberlain
      Jun 11 '13 at 14:57






    • 1




      number of corrections: 1. your method has a void return type and, you are returning something else (return SAIDA;) 2. you have initialize an SqlDataAdapter and it is never used. 3. ExecuteScalar(); returns an object, needs type conversion.
      – Sam Saarian
      Dec 5 '17 at 22:18













    up vote
    32
    down vote



    accepted







    up vote
    32
    down vote



    accepted






    You can't just call the function name, you will need to write an inline SQL statement which makes use of the UDF:



    SqlCommand Totalf = new SqlCommand("SELECT dbo.Tcupom(@code)", conex1);


    And remove the CommandType, this isn't a Stored Procedure, its a User Defined Function.



    In all:



    public void TotalCupom(int cupom)
    {
    float SAIDA;
    SqlDataAdapter da2 = new SqlDataAdapter();
    if (conex1.State == ConnectionState.Closed)
    {
    conex1.Open();
    }
    SqlCommand Totalf = new SqlCommand("SELECT dbo.Tcupom(@code)", conex1);
    SqlParameter code1 = new SqlParameter("@code", SqlDbType.Int);
    code1.Value = cupom;
    SAIDA = Totalf.ExecuteScalar();

    return SAIDA;
    }





    share|improve this answer














    You can't just call the function name, you will need to write an inline SQL statement which makes use of the UDF:



    SqlCommand Totalf = new SqlCommand("SELECT dbo.Tcupom(@code)", conex1);


    And remove the CommandType, this isn't a Stored Procedure, its a User Defined Function.



    In all:



    public void TotalCupom(int cupom)
    {
    float SAIDA;
    SqlDataAdapter da2 = new SqlDataAdapter();
    if (conex1.State == ConnectionState.Closed)
    {
    conex1.Open();
    }
    SqlCommand Totalf = new SqlCommand("SELECT dbo.Tcupom(@code)", conex1);
    SqlParameter code1 = new SqlParameter("@code", SqlDbType.Int);
    code1.Value = cupom;
    SAIDA = Totalf.ExecuteScalar();

    return SAIDA;
    }






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Mar 16 at 9:27









    Massimiliano Kraus

    2,33741532




    2,33741532










    answered Jun 11 '13 at 14:49









    Curt

    75.3k50230316




    75.3k50230316












    • Actually because he did Totalf.CommandType = CommandType.StoredProcedure he can just call the function name.
      – Scott Chamberlain
      Jun 11 '13 at 14:50












    • @ScottChamberlain Are you sure? What if there was a stored procedure called Tcupom? Surely SQL Server would get confused...
      – Curt
      Jun 11 '13 at 14:52








    • 2




      No, you are right, I just realized he was using a scalar function, not a table based function. I don't know if those can be called via SqlCommand set as StoredProcedure
      – Scott Chamberlain
      Jun 11 '13 at 14:53








    • 2




      Refresh your page, I agree with you now.
      – Scott Chamberlain
      Jun 11 '13 at 14:57






    • 1




      number of corrections: 1. your method has a void return type and, you are returning something else (return SAIDA;) 2. you have initialize an SqlDataAdapter and it is never used. 3. ExecuteScalar(); returns an object, needs type conversion.
      – Sam Saarian
      Dec 5 '17 at 22:18


















    • Actually because he did Totalf.CommandType = CommandType.StoredProcedure he can just call the function name.
      – Scott Chamberlain
      Jun 11 '13 at 14:50












    • @ScottChamberlain Are you sure? What if there was a stored procedure called Tcupom? Surely SQL Server would get confused...
      – Curt
      Jun 11 '13 at 14:52








    • 2




      No, you are right, I just realized he was using a scalar function, not a table based function. I don't know if those can be called via SqlCommand set as StoredProcedure
      – Scott Chamberlain
      Jun 11 '13 at 14:53








    • 2




      Refresh your page, I agree with you now.
      – Scott Chamberlain
      Jun 11 '13 at 14:57






    • 1




      number of corrections: 1. your method has a void return type and, you are returning something else (return SAIDA;) 2. you have initialize an SqlDataAdapter and it is never used. 3. ExecuteScalar(); returns an object, needs type conversion.
      – Sam Saarian
      Dec 5 '17 at 22:18
















    Actually because he did Totalf.CommandType = CommandType.StoredProcedure he can just call the function name.
    – Scott Chamberlain
    Jun 11 '13 at 14:50






    Actually because he did Totalf.CommandType = CommandType.StoredProcedure he can just call the function name.
    – Scott Chamberlain
    Jun 11 '13 at 14:50














    @ScottChamberlain Are you sure? What if there was a stored procedure called Tcupom? Surely SQL Server would get confused...
    – Curt
    Jun 11 '13 at 14:52






    @ScottChamberlain Are you sure? What if there was a stored procedure called Tcupom? Surely SQL Server would get confused...
    – Curt
    Jun 11 '13 at 14:52






    2




    2




    No, you are right, I just realized he was using a scalar function, not a table based function. I don't know if those can be called via SqlCommand set as StoredProcedure
    – Scott Chamberlain
    Jun 11 '13 at 14:53






    No, you are right, I just realized he was using a scalar function, not a table based function. I don't know if those can be called via SqlCommand set as StoredProcedure
    – Scott Chamberlain
    Jun 11 '13 at 14:53






    2




    2




    Refresh your page, I agree with you now.
    – Scott Chamberlain
    Jun 11 '13 at 14:57




    Refresh your page, I agree with you now.
    – Scott Chamberlain
    Jun 11 '13 at 14:57




    1




    1




    number of corrections: 1. your method has a void return type and, you are returning something else (return SAIDA;) 2. you have initialize an SqlDataAdapter and it is never used. 3. ExecuteScalar(); returns an object, needs type conversion.
    – Sam Saarian
    Dec 5 '17 at 22:18




    number of corrections: 1. your method has a void return type and, you are returning something else (return SAIDA;) 2. you have initialize an SqlDataAdapter and it is never used. 3. ExecuteScalar(); returns an object, needs type conversion.
    – Sam Saarian
    Dec 5 '17 at 22:18












    up vote
    0
    down vote













    ...

    try
    {
    if (connectionState != ConnectionState.Open)
    conn.Open();
    using (var cmd = conn.CreateCommand())
    {
    cmd.CommandText = "udfName";
    cmd.CommandType = CommandType.StoredProcedure;

    foreach (var cmdParam in sqlParams)
    {
    cmd.Parameters.Add(cmdParam);
    }


    var retValParam = new SqlParameter("RetVal", SqlDbType.Int)
    {
    //Set this property as return value
    Direction = ParameterDirection.ReturnValue
    };

    cmd.Parameters.Add(retValParam);
    cmd.ExecuteScalar();

    retVal = retValParam.Value;
    }
    }
    finally
    {
    if (connectionState == ConnectionState.Open)
    conn.Close();
    }

    ...





    share|improve this answer

























      up vote
      0
      down vote













      ...

      try
      {
      if (connectionState != ConnectionState.Open)
      conn.Open();
      using (var cmd = conn.CreateCommand())
      {
      cmd.CommandText = "udfName";
      cmd.CommandType = CommandType.StoredProcedure;

      foreach (var cmdParam in sqlParams)
      {
      cmd.Parameters.Add(cmdParam);
      }


      var retValParam = new SqlParameter("RetVal", SqlDbType.Int)
      {
      //Set this property as return value
      Direction = ParameterDirection.ReturnValue
      };

      cmd.Parameters.Add(retValParam);
      cmd.ExecuteScalar();

      retVal = retValParam.Value;
      }
      }
      finally
      {
      if (connectionState == ConnectionState.Open)
      conn.Close();
      }

      ...





      share|improve this answer























        up vote
        0
        down vote










        up vote
        0
        down vote









        ...

        try
        {
        if (connectionState != ConnectionState.Open)
        conn.Open();
        using (var cmd = conn.CreateCommand())
        {
        cmd.CommandText = "udfName";
        cmd.CommandType = CommandType.StoredProcedure;

        foreach (var cmdParam in sqlParams)
        {
        cmd.Parameters.Add(cmdParam);
        }


        var retValParam = new SqlParameter("RetVal", SqlDbType.Int)
        {
        //Set this property as return value
        Direction = ParameterDirection.ReturnValue
        };

        cmd.Parameters.Add(retValParam);
        cmd.ExecuteScalar();

        retVal = retValParam.Value;
        }
        }
        finally
        {
        if (connectionState == ConnectionState.Open)
        conn.Close();
        }

        ...





        share|improve this answer












        ...

        try
        {
        if (connectionState != ConnectionState.Open)
        conn.Open();
        using (var cmd = conn.CreateCommand())
        {
        cmd.CommandText = "udfName";
        cmd.CommandType = CommandType.StoredProcedure;

        foreach (var cmdParam in sqlParams)
        {
        cmd.Parameters.Add(cmdParam);
        }


        var retValParam = new SqlParameter("RetVal", SqlDbType.Int)
        {
        //Set this property as return value
        Direction = ParameterDirection.ReturnValue
        };

        cmd.Parameters.Add(retValParam);
        cmd.ExecuteScalar();

        retVal = retValParam.Value;
        }
        }
        finally
        {
        if (connectionState == ConnectionState.Open)
        conn.Close();
        }

        ...






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 19 at 17:46









        Yargicx

        5401722




        5401722






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f17047057%2fcalling-sql-defined-function-in-c-sharp%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            404 Error Contact Form 7 ajax form submitting

            How to know if a Active Directory user can login interactively

            TypeError: fit_transform() missing 1 required positional argument: 'X'