17

I have a function defined in SQL Server (that takes a string and a int) how do I call it with ADO.NET?

(If it is 100% same as calling a stored proc, please just say so, as there a lot of examples on calling stored procs about)

Ian Ringrose
  • 51,220
  • 55
  • 213
  • 317

1 Answers1

30

The only difference is that you must have a special paramter added for the return value

See: MySqlCommand call function

  using (var connection = new SqlConnection("ConnectionString"))
  using (var command = connection.CreateCommand())
  {
    command.CommandType = CommandType.StoredProcedure;
    command.CommandText = "MyFunction";

    SqlParameter returnValue = command.Parameters.Add("@RETURN_VALUE", SqlDbType.Int);
    returnValue.Direction = ParameterDirection.ReturnValue;

    connection.Open();
    command.ExecuteNonQuery();

    return returnValue.Value;
  } 
Community
  • 1
  • 1
Chris Baxter
  • 16,083
  • 9
  • 51
  • 72
  • @SašaĆetković The referenced link is MySqlCommand since it was a pre-existing answer, the code snippet in the answer is SQL-Server – Chris Baxter Jul 23 '20 at 18:05