Question

I need to execute a stored procedure on a database. This is what I got so far that works:

protected DbProviderFactory dbProviderFactory;
this.dbProviderFactory = DalFactory.GetFactory(this.adapterConfiguration);

DbConnection dbConnection = dbProviderFactory.CreateConnection();

dbConnection.ConnectionString = this.adapterConfiguration.DatabaseInformation.ExternalDatabaseInformation.connectionString;
            try
            {
                dbConnection.Open();
            }
            catch (Exception e)
            {

                throw;
            }

I suspect that DbCommand would do it, but haven't found anything working. Let's say that the stored procedure by the name "initialize" has to be executed. How do I do that?

Was it helpful?

Solution

For SqlServer, this could be like this :

DbCommand command = new SqlCommand();
command.CommandType = System.Data.CommandType.StoredProcedure;
command.CommandText = "<your stored proc>";
command.Connection = dbConnection;

SqlParameter param1 = new SqlParameter("<your parameter>", MyVar);
command.Parameters.Add(param1);
//[...]

SqlParameter returnValue = new SqlParameter("ReturnValue", User);
returnValue.Direction = System.Data.ParameterDirection.ReturnValue;
command.Parameters.Add(returnValue);

command.Connection.Open();
command.ExecuteNonQuery();
int result = (int)command.Parameters["ReturnValue"].Value;
command.Connection.Close();

OTHER TIPS

Create a command, the command text should be the name of the SP, and the command type should be StoredProcedure.

I'm doing dynamic queries in most of my app, but have EF too. I pass a _ctx EF DbContext to run my stored procedure. I'm sure there's a way to do this all in sql, but I haven't figured it out yet.

            using (_ctx)
            {
                if (_ctx.Database.Connection.State != ConnectionState.Open)
                    _ctx.Database.Connection.Open();
                foreach (var name in _tableNames)
                {
                    using (var cmd = _ctx.Database.Connection.CreateCommand())
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.CommandText = @"UpdateRMRowsToUpload";
                        cmd.Parameters.Add(new SqlParameter("@tableName", SqlDbType.VarChar));
                        cmd.Parameters["@tableName"].Direction = Input;
                        cmd.Parameters["@tableName"].Value = name;
                        cmd.ExecuteNonQuery();
                    }
                }
                if (_ctx.Database.Connection.State == ConnectionState.Open)
                    _ctx.Database.Connection.Close();
            }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top