c# - 将存储过程中的 Select Query 的结果返回到列表

标签 c# asp.net sql-server

我正在编写一个存储过程,目前它只包含一个SELECT 查询。它将被扩展以做许多其他事情,这就是为什么它必须是一个存储过程,但现在,它是一个简单的查询。

像这样:

SELECT name, occupation, position 
FROM jobs 
WHERE ...

我希望返回此查询的结果以在 C# 中使用。我想将它添加到列表中,以便我可以将它绑定(bind)到 GridView 组件。

虽然我不知道该怎么做。如果我必须在返回所有选定数据后将其插入到列表中,那没关系,我只需要知道如何正确返回数据以便我可以做到这一点。

不过,如果我能以一种可以直接弹出到列表中的格式返回它,那就太理想了。

最佳答案

在存储过程中,你只需要像下面这样编写选择查询:

CREATE PROCEDURE TestProcedure
AS
BEGIN
    SELECT ID, Name 
    FROM Test
END

在C#端,可以使用Reader、datatable、a​​dapter访问。

Susanna Floora 刚刚解释了如何使用适配器。

使用阅读器:

SqlConnection connection = new SqlConnection(ConnectionString);

command = new SqlCommand("TestProcedure", connection);
command.CommandType = System.Data.CommandType.StoredProcedure;
connection.Open();
SqlDataReader reader = command.ExecuteReader();

List<Test> TestList = new List<Test>();
Test test = null;

while (reader.Read())
{
    test = new Test();
    test.ID = int.Parse(reader["ID"].ToString());
    test.Name = reader["Name"].ToString();
    TestList.Add(test);
}

gvGrid.DataSource = TestList;
gvGrid.DataBind();

使用数据表:

SqlConnection connection = new SqlConnection(ConnectionString);

command = new SqlCommand("TestProcedure", connection);
command.CommandType = System.Data.CommandType.StoredProcedure;
connection.Open();

DataTable dt = new DataTable();

dt.Load(command.ExecuteReader());
gvGrid.DataSource = dt;
gvGrid.DataBind();

希望对您有所帮助。 :)

关于c# - 将存储过程中的 Select Query 的结果返回到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18901545/

相关文章:

c# - 通过windows服务打开浏览器渲染和截图selenium .Net中的webgl页面

c# - 无法访问 Controller 中带参数的操作方法

asp.net - .NET VirtualPathProviders 和预编译

c# - 使用 LINQ 进行查询,其中上下文与对象列表中的多个参数相匹配

c# - 如何获取类的属性列表?

c# - 绘制贝塞尔曲线的半弧

sql - 将日期时间转换为美国和欧洲日期时间

sql - 创建存储过程(如果尚不存在)

c# - 方法封装的性能成本

asp.net - 表单 css 反射(reflect)到 ajax 日历 css