Reputation: 6053
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#?
Upvotes: 0
Views: 1080
Reputation: 28338
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";
Upvotes: 1