CREATE FUNCTION dbo.GetEmail(@uname varchar(10))TURNS varchar(50) AS BEGIN declare @email varchar(50) select @email = email from users where uname = @uname; return @email; END
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CallFunction.aspx.cs" Inherits="CallFunction" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title>Calling Stored Function</title> </head> <body> <form id="form1" runat="server"> <div> <h1>Calling Stored Function</h1> Enter username : <asp:TextBox ID="txtUsername" runat="server" Width="230px"></asp:TextBox> <p /> <asp:Button ID="btnGetEmail" runat="server" Text="Get Email" onclick="btnGetEmail_Click" /> <p /> <asp:Label ID="lblEmail" runat="server" Text=""></asp:Label> </div> </form> </body> </html>
using System; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; public partial class callfunction : System.Web.UI.Page { protected void btnGetEmail_Click(object sender, EventArgs e) { SqlConnection con = new SqlConnection(@"Data Source=localhost\sqlexpress;Initial Catalog=msdb;Integrated Security=True"); try { con.Open(); SqlCommand cmd= new SqlCommand("getemail",con); cmd.CommandType = CommandType.StoredProcedure; // add parameter for return value SqlParameter rv = new SqlParameter("@returnvalue",SqlDbType.VarChar,50); rv.Direction = ParameterDirection.ReturnValue; cmd.Parameters.Add(rv); // add input parameter cmd.Parameters.AddWithValue ("@uname", txtUsername.Text); cmd.ExecuteNonQuery (); // return value is in the parameter @returnvalue Object email = cmd.Parameters["@returnvalue"].Value; // If return value is not null then use value if (DBNull.Value != email) lblEmail.Text = email.ToString(); else lblEmail.Text = "Sorry! User Not Found"; } catch(Exception ex) { lblEmail.Text = ex.Message; } finally { con.Close(); } } }