7
public void CreateMySqlCommand() 
 {
    SqlCommand myCommand = new SqlCommand();
    myCommand.CommandText = "SELECT * FROM Categories ORDER BY CategoryID";
    myCommand.CommandTimeout = 15;
    myCommand.CommandType = CommandType.Text;
 }

Can I use Sql Server functions in myCommand.CommandText and why?

2
  • 1
    Can you explain what you mean by "SQL Server Functions" do you mean stored procedures? Commented Feb 24, 2013 at 3:57
  • "why"?! Do you mean "how"? Commented Feb 24, 2013 at 4:00

2 Answers 2

19

If you mean, SQL Server user defined functions. Then, yes; you can use it normally like:

myCommand.CommandText = "SELECT fn_Yourfunctionname(@parameternames)";
myCommand.CommandType = CommandType.Text;
myCommand.Parameters.Add(new SqlParameter("@parameternames", ...

The reason it works is because this is the way that functions are called in SQL Server directly.

Sign up to request clarification or add additional context in comments.

Comments

0

Another approach:

    public T ExecuteScalarFunction<T>(string functionName, List<SqlParameter> parameters, SqlDbType returnSqlType) where T : new()
    {
        using (var conn = new SqlConnection(CTX.Database.GetDbConnection().ConnectionString))
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();

            using (var cmd = new SqlCommand(functionName, conn)) { 
                cmd.CommandType = CommandType.StoredProcedure;
                SqlCommandBuilder.DeriveParameters(cmd);

                foreach (var parameter in parameters)
                {
                    cmd.Parameters.Add(parameter);
                }

                cmd.Parameters.Add("@RETURN_VALUE", returnSqlType).Direction = ParameterDirection.ReturnValue;

                cmd.ExecuteNonQuery();
                return (T)cmd.Parameters["@RETURN_VALUE"].Value;
            }
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.