sql server -如何获取一个“EXEC storedProcedure()”的结果在c#

本文关键字:EXEC storedProcedure 结果 一个 server 何获取 sql 获取 | 更新日期: 2023-09-27 18:02:12

不要问我为什么,但是我想在sqlCommand对象中放入这样的东西:

sqlConnection a = new sqlConection(...);
sqlCommand b = new sqlCommand("EXEC storedProcedure()", a);
sqlDataAdapter c = new sqlDataAdapter(b);
DataTable d = new DataTable();
c.Fill(d);

因此,当存储过程进行插入时,行被成功添加,但是代码抛出异常。

我知道存在sqlCommand。CommandType专门用于存储过程,但我的架构需要这样做

sql server -如何获取一个“EXEC storedProcedure()”的结果在c#

设置适配器的"SelectCommand"属性

var cmd = new SqlCommand("EXEC storedProcedure()", a);
cmd.CommandType = CommandType.StoredProcedure; //set command property
//..
var adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd; //set adapter command for select query

和你的命令类型必须是CommandType.StoredProcedure来执行SP,你的架构不需要这个吗?问他一个好理由。

您的SQL语法是关闭的。

From http://technet.microsoft.com/en-us/library/ms188332.aspx:

USE AdventureWorks2012;
GO
DECLARE @CheckDate datetime;
SET @CheckDate = GETDATE();
EXEC dbo.uspGetWhereUsedProductID 819, @CheckDate;
GO
所以你的代码应该是:
new sqlCommand("EXEC storedProcedure", a);

虽然有很多方法可以做同样的事情,但当你按照框架建议的方式去做时,有些事情会做得最好。

在这种情况下,运行存储过程时可能发生几件事情,这取决于它是哪个过程。它可能返回一组行,或者几组行,或者什么都不返回。我们已经可以做一些事情来处理所有这些情况,感谢。net框架。

这里是一些扩展代码,我在过去使用的任何SP返回一个或多个行集:

public static DataSet ExecuteStoredProcedure(this SqlConnection connection, string SPName, params object[] parameters)
{
    using (var cmd = connection.CreateCommand())
    {
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = SPName;
        cmd.CommandTimeout = 60;
        if (connection.State != ConnectionState.Open)
            connection.Open();
        SqlCommandBuilder.DeriveParameters(cmd);
        int index = 1;
        foreach (object p in parameters)
        {
            if (index >= cmd.Parameters.Count)
                break;
            cmd.Parameters[index++].Value = (p == null ? DBNull.Value : p);
        }
        using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
        {
            DataSet res = new DataSet();
            adapter.Fill(res);
            return res;
        }
    }
}

处理非行集返回值和输出参数需要更多的工作,但这将满足您的直接需求:

var conn = new SqlConnection("some connection string");
DataSet ds = conn.ExecuteStoredProcedure("storedProcedure");
DataTable d = ds == null ? null : ds.Tables.Length < 1 ? null : ds.Tables[0];