How to call Sql function from code behind

In this article I'm going to explain How to call Sql function from code behind file.

In this article I'm going to explain how to call function from code behind file. User Defined function can be accept both input and return
parameters. These can be called from code behind file in this example. Function and Store procedure as same but function return value
but stored procedure may or may not return value. Function are database object in sql server it contains collection of sql statements.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Mail;
using System.Net;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page

protected void Page_Load(object sender, EventArgs e)
SqlConnection con = new SqlConnection("server=pc;uid=sa;password=p@s;database=databasename");

SqlCommand sqlcmd = new SqlCommand("select dbo.[AddionofTwoNumbers](@Number1, @Number2,@Number3)", con);
sqlcmd.CommandType = CommandType.Text;
sqlcmd.Parameters.AddWithValue("@Number1", 10);
sqlcmd.Parameters.AddWithValue("@Number2", 20);
sqlcmd.Parameters.AddWithValue("@Number3", 30);
DataSet dsResutl = new DataSet();
string stroutput = string.Empty;
stroutput =Convert.ToString((Int32)sqlcmd.ExecuteScalar());

catch (Exception ex)
Response.Write("<script language='javascript'>alert('"+ex.Message.ToString()+"');</script>");

CREATE FUNCTION [dbo].[AddionofTwoNumbers]


@Number1 int,
@Number2 int,
@Number3 int





-- Declare the return variable here

DECLARE @Output int

SELECT @Output = @Number1 + @Number2+ @Number3;

-- Return the result of the function

RETURN @Output


A function can be executed in below lines in sql server

Select dbo.[AddionofTwoNumbers](1,2,3)


No responses found. Be the first to comment...

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: