将参数化的sql查询作为参数传递给不工作的存储过程
本文关键字:参数传递 工作 存储过程 参数 sql 查询 | 更新日期: 2023-09-27 18:02:43
我想将参数化的SQL查询作为参数传递给SQL Server中的存储过程,但无法使其工作。这是我尝试过的
存储过程代码:
CREATE PROCEDURE [dbo].[SroredProc]
@Qry nvarchar(max)
AS
BEGIN
SET NOCOUNT ON;
EXEC sp_executesql @Qry;
End
c# code
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);
我认为你应该像下面这样。同样,这么早打开连接是没有意义的;在调用/执行命令之前打开它。
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);
有两件事:
您忘记将连接关联到命令
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
请看一下我在你的代码中添加的注释。
我真的明白你想做什么。您正在尝试对发送给存储过程的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);