簡體   English   中英

將參數化的SQL查詢作為參數傳遞給存儲過程不起作用

[英]Passing parameterized sql query as parameter to a stored procedure not working

我想將參數化的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);

我認為您應該像下面這樣。 同樣,如此早地打開連接沒有意義。 而是在調用/執行命令之前將其打開。

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM