C# Tips

C# Tip Article

Calling SQL Function from C#

A Simple example of calling a SQL function by using ADO.NET.

While it is not common, sometimes there are times when calling it directly from C#. So here is simple code snippet. Let's assume the SQL function is a plain vanilla scalar-valued function that has one input parameter.

public string CallSqlFunc(string id)
{
	string strConn = ConfigurationManager.AppSettings["MyConnection"];
	using (var conn = new SqlConnection(strConn))
	{
		conn.Open();                
		var cmd = new SqlCommand("SELECT dbo.MyFunction(@id)", conn);
		cmd.CommandType = CommandType.Text;
		cmd.Parameters.AddWithValue("@id", id);                                

		object retVal = cmd.ExecuteScalar();
		return retVal.ToString();
	}
}