简体   繁体   中英

INSERT EXEC from DbCommand

I'm trying to execute the results of a stored procedure that takes parameters into a temporary table.

// Create #temptable
// ..

using (DbCommand command = connection.CreateCommand())
{
    command.CommandText = "INSERT #temptable EXEC [MystoredProcThatHasParams]";
    command.CommandType = CommandType.StoredProcedure;
    command.Parameters.Add(someObject)
    command.ExecuteNonQuery();
}

Output:

Could not find stored procedure ''.

If I remove command.CommandType = CommandType.StoredProcedure , I get:

Procedure or function 'MystoredProcThatHasParams' expects parameter '@p1' which was not supplied

Is it possible to save the output of a stored procedure that takes parameters from a query in C#?

The command type StoredProcedure uses a special, higher-performance method for connecting to SQL Server (an RPC call), which requires that the command text be exactly the name of a stored procedure. You cannot include Transact-SQL in the command text if you want to use CommandType.StoredProcedure .

Instead, you need to use CommandType.Text and embed the parameters into the SQL string yourself:

cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT #temptable EXEC [MystoredProcThatHasParams] @Param1, @Param2";
cmd.Parameters.Add("@Param1", SqlDbType.Int).Value = 1;
cmd.Parameters.Add("@Param2", SqlDbType.VarChar, 100).Value = "Test";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM