【问题标题】:Calling stored procedure via query and getting return value in C# without output parameters通过查询调用存储过程并在没有输出参数的C#中获取返回值
【发布时间】:2009-07-06 14:12:40
【问题描述】:

有没有我可以通过 EXEC 执行存储过程(所以不在 C# 中指定 CommandType.StoredProcedure)并获得结果?

我尝试执行查询

DECLARE @R int 
EXEC @R = proc p1, p2

然后抓住@R但没有成功。

我不想要的是通过添加参数并使用ParameterDirection.ReturnValue获取结果的常规方式。

我会很感激任何信息。 泰。

编辑

有人问为什么。

我需要创建一个小的控制台程序来运行任何存储过程并获得它返回的任何类型的结果。该应用程序接受带有数据库连接描述和 sp 名称的 .config 文件。

现在,如果我按照通常的方式进行操作,我需要为每个参数配置输入,或者如果调用以通常的查询格式指定,那么我需要自己解析它。用户需要了解参数详细信息等...

这就是我选择 exec 方法的原因。用户可以在配置文件中一键指定存储过程和参数。

   <add key="Procedure" value="dbo.TEST 10,20"/>

不要想太多。从事此类程序的人不懂编程,他们知道需要将一些文本作为参数(即隐式转换很神秘)

该程序通常不会接受除初始配置之外的任何用户参数,因此不存在sql注入等,即使关注注入检查也可以移至SP级别。

c 的实现变得微不足道:

    const string runFormat = "exec ('declare @r varchar (1024);EXEC @r={0}{1};select @r')";

    public bool Run(string parameters, out string result) {
        SqlConnection con = new SqlConnection( connectionString );

        SqlCommand cmnd = new SqlCommand(String.Empty, con);
        cmnd.CommandText = String.Format(runFormat, storedProcedure, parameters ?? String.Empty);  

        try {
            con.Open();
            result = (string)cmnd.ExecuteScalar();
        }
        catch (Exception e) {
            result = e.Message;
            return false;
        }
        return true;
    }    

【问题讨论】:

  • 你说了你不想做的事,但不是你想做的事。你想通过不使用参数来完成什么?

标签: c# sql-server stored-procedures ado.net


【解决方案1】:

尝试在 C# 中运行此查询:

exec ('declare @r int;EXEC @r=testing 1,2;select @r')

【讨论】:

  • Ty 伙计,正是我所需要的。我通过执行标量得到结果。
【解决方案2】:

您无法获取@R,因为它是在不了解外部世界的批次中声明的。 BLToolkit 救援(大致):

[SqlQuery("declare @r int; exec @r = proc @p1, @p2; return @r")]
public abstract object ExecProc(int @p1, int @p2);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-22
    • 1970-01-01
    • 2017-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多