在 C# 中使用 SQL 查询。定义存储过程的问题

Using SQL queries in C#. Trouble with defining stored procedure

我在下面分享我的代码片段:

string str = "select * from contacts";
DataSet dt = Global.getdatatablefromquery(str);
ExcelGrid.DataSource = dt;
ExcelGrid.DataBind();

我正在将我的所有查询更改为存储过程,但我不知道我将如何在此代码中定义我的存储过程?我想要这样的东西:

string str = "storedprocedurename";
DataSet dt = Global.getdatatablefromquery(str);
ExcelGrid.DataSource = dt;
ExcelGrid.DataBind();

你有2个选择(据我所知)

1. 通过指定 EXEC explicitly.

作为 Text 执行

例如:

cmd = new SqlCommand("EXEC storedprocedurename(@p1, @p2)");
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("@p1", 1);
cmd.Parameters.Add("@p2", 2);

2. 您可以将 CommandType 用作 StoredProcedure

例如:

cmd = new SqlCommand("storedprocedurename");
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@p1", 1);
cmd.Parameters.Add("@p2", 2);

The difference between the 2 approaches is how message pumping happens.(source)

使用将 CommandType 明确指定为 StoredProcedure 的第二种方法更加清晰明了。