简体   繁体   English

从DbCommand插入EXEC

[英]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: 如果删除command.CommandType = CommandType.StoredProcedurecommand.CommandType = CommandType.StoredProcedure得到:

Procedure or function 'MystoredProcThatHasParams' expects parameter '@p1' which was not supplied 过程或函数“ MystoredProcThatHasParams”期望未提供的参数“ @ p1”

Is it possible to save the output of a stored procedure that takes parameters from a query in C#? 是否可以保存使用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. 命令类型StoredProcedure使用一种特殊的高性能方法来连接到SQL Server(RPC调用),该方法要求命令文本准确地是存储过程的名称。 You cannot include Transact-SQL in the command text if you want to use CommandType.StoredProcedure . 如果要使用CommandType.StoredProcedure则不能在命令文本中包含Transact-SQL。

Instead, you need to use CommandType.Text and embed the parameters into the SQL string yourself: 相反,您需要使用CommandType.Text并将参数自己嵌入到SQL字符串中:

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";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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