将参数化sql查询作为参数传递给不工作的存储过程

时间:2014-05-11 17:21:25

标签: c# sql sql-server tsql stored-procedures

我想将参数化的SQL查询作为参数传递给SQL Server中的存储过程,但无法使其工作。这就是我尝试过的事情

存储过程代码:

CREATE PROCEDURE [dbo].[SroredProc]
   @Qry nvarchar(max)
AS
BEGIN
   SET NOCOUNT ON;
   EXEC sp_executesql @Qry;
End

C#代码

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["mycon"].ConnectionString);
SqlCommand cmd = new SqlCommand();
string s = "select id,name from tbl where id=@id";
con.Open();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = s;
cmd.Parameters.AddWithValue("@id", 1);
cmd= new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "SroredProc";
cmd.Parameters.AddWithValue("@Qry", s);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);

3 个答案:

答案 0 :(得分:0)

我认为你应该像下面这样。同样,没有必要这么早地打开连接;而是在调用/执行命令之前打开它。

int id = 1;
SqlConnection con = new 
SqlConnection(ConfigurationManager.ConnectionStrings["mycon"].ConnectionString);
SqlCommand cmd = new SqlCommand();
string s = string.format("select id,name from tbl where id={0}",id);
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "SroredProc";
cmd.Parameters.AddWithValue("@Qry", s);
DataTable dt = new DataTable();
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);

答案 1 :(得分:0)

有两件事:

您忘记将连接与命令

相关联
cmd.Connection = con;

我会将字符串s的声明更改为,您的@Qry参数永远不会填充id的实际值。

int id = 1; // <- insert your value here.
string s = String.Format("select id,name from tbl where id={0}", id);
//cmd.Parameters.AddWithValue("id", 1);  <-- remove this line

答案 2 :(得分:0)

请查看我添加到您的代码中的评论。

我真的明白你想做什么。您正在尝试参数化发送到存储过程的tsql语句,然后参数化存储过程。不幸的是,你做不到。 (您可以参数化TSQL语句。您不能参数化参数。)

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["mycon"].ConnectionString);
SqlCommand cmd = new SqlCommand();
string s = "select id,name from tbl where id=@id";
con.Open();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = s;
cmd.Parameters.AddWithValue("@id", 1);  // You set the param here
cmd= new SqlCommand();  // You just effectively erased the previous 4 lines of code with this line.
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "SroredProc";
cmd.Parameters.AddWithValue("@Qry", s);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);