我正在编写一个存储过程,目前它只包含一个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、adapter访问。
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/