gpt4 book ai didi

c# - 从 SQL 返回 2 个结果

转载 作者:行者123 更新时间:2023-11-30 15:23:41 25 4
gpt4 key购买 nike

如果我有一个存储过程是

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

关于c# - 从 SQL 返回 2 个结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34210717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com