数据库
首页 > 数据库> > c#-从SQL返回2个结果

c#-从SQL返回2个结果

作者:互联网

如果我有一个存储过程是

Alter dbo.Testing
    Select userid from masterdb
    where employed = 'Yes'

    Select Count(*) from leftfield
    where pin is not null

如何将每个查询返回的结果存储在单独的数据集中?

伪代码:

firstdataset = Select userid from masterdb where employed = 'Yes'

seconddataset = select count(*) from leftfield where pin is not null

编辑

我使用它来将1个结果集从存储过程返回到C#数据集.是否可以返回大于1的值?

public DataSet RunStoredProc(string databaseConnection)
{
    ds = new DataSet();  

    DSqlQueryBuilder = new StringBuilder();

    SqlQueryBuilder.Append("exec dbo.StoredProc "); 

    SqlConnection = new SqlConnection(connectionString);
    SqlCommand = new SqlCommand(sqlQuery, SqlConnection);

    SqlConnection.Open();
    SqlCommand.CommandTimeout = 0;  
    ds = new DataSet();

    SqlDataAdapter = new SqlDataAdapter(SqlCommand);            
    SqlDataAdapter.Fill(ds, "Data");

    return ds;
}

编辑#2

public DataSet RunStoredProc(string databaseConnection)
{
    ds = new DataSet();  
    DSqlQueryBuilder = new StringBuilder();
    SqlQueryBuilder.Append("exec dbo.StoredProc "); 
    //Error 1 On Line Below
    ds = ExecuteSqlQuery(databaseConnection, SqlQueryBuilder.ToString());
    return ds;
}
public List<DataTable> RunStoredProc(string databaseConnection)
{
    var dataTables = new List<DataTable>();  
    DSqlQueryBuilder = new StringBuilder();
    SqlQueryBuilder.Append("exec dbo.StoredProc "); 
    SqlConnection = new SqlConnection(connectionString);
    SqlCommand = new SqlCommand(sqlQuery, SqlConnection);
    var reader = SqlCommand.ExecuteReader();
    DataTable dt1 = new DataTable();
    dt1.Load(reader);
    dataTables.Add(dt1);
    DataTable dt2 = new DataTable();
    dt2.Load(reader);
    dataTables.Add(dt2);
    return dataTables;
}

Error # 1
Cannot implicitly convert type ‘System.Collections.Generic.List’ to ‘System.Data.DataSet’

解决方法:

您可以这样做:

Alter dbo.Testing

-- Declare your variables
Declare @userId AS INT;
Declare @count AS INT;

-- Set the value
Select @userId = userid from masterdb where employed = 'Yes';
Select @count = Count(1) from leftfield where pin is not null;

-- Return the values
Select @userId, @count;

**编辑添加功能以连接到数据库**

获取您的值的示例函数:

static DataSet sqlTest(string connectionString)
{
    using (var sqlConnection = new SqlConnection(connectionString))
    {
        sqlConnection.Open();
        var sqlCommand = new SqlCommand("exec dbo.StoredProc", sqlConnection);
        var dataSet = new DataSet();
        var sqlDataAdapter = new SqlDataAdapter(sqlCommand);
        sqlDataAdapter.Fill(dataSet, "Data");

        // you can access your values like that:
        var userId = dataSet.Tables["Data"].Rows[0][0];
        var count = dataSet.Tables["Data"].Rows[0][1];

        return dataSet;
    }
}

标签:sql-server-2008-r2,webforms,c
来源: https://codeday.me/bug/20191027/1945673.html