0
我目前有一個jQuery自動完成插件的查詢字符串,但應該使用存儲過程。任何人都可以幫助我轉換?我這樣做似乎沒有工作。轉換爲存儲過程
原始ASHX
public class Search_CS : IHttpHandler {
public void ProcessRequest (HttpContext context) {
string prefixText = context.Request.QueryString["q"];
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["Rollup2ConnectionString"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
//cmd.CommandText = "select NUID from T_USER where " +
//"NUID like @SearchText + '%'";
cmd.CommandText = "select rtrim(NUID) NUID, rtrim(FNAME) FNAME, rtrim(LNAME) LNAME from T_USER where NUID like @SearchText + '%' OR FNAME like @SearchText + '%' OR LNAME like @SearchText + '%'";
cmd.Parameters.AddWithValue("@SearchText", prefixText);
cmd.Connection = conn;
StringBuilder sb = new StringBuilder();
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
sb.Append(sdr["NUID"].ToString() + " ").Append(sdr["FNAME"].ToString() + " ").Append(sdr["LNAME"].ToString() + " ")
.Append(Environment.NewLine);
}
}
conn.Close();
context.Response.Write(sb.ToString());
}
}
}
新ASHX存儲過程:
public class Search_CS : IHttpHandler {
public void ProcessRequest (HttpContext context) {
string prefixText = context.Request.QueryString["q"];
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["Rollup2ConnectionString"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
//cmd.CommandText = "select NUID from T_USER where " +
//"NUID like @SearchText + '%'";
cmd.CommandText = "SP_AUTOCOMPLETE";
cmd.Parameters.AddWithValue("@SearchText", prefixText);
cmd.Parameters.Add(new SqlParameter("@SearchText", SqlDbType.VarChar));
cmd.Parameters["@SearchText"].Value = prefixText;
cmd.Connection = conn;
StringBuilder sb = new StringBuilder();
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
sb.Append(sdr["NUID"].ToString() + " ").Append(sdr["FNAME"].ToString() + " ").Append(sdr["LNAME"].ToString() + " ")
.Append(Environment.NewLine);
}
}
conn.Close();
context.Response.Write(sb.ToString());
}
}
}
存儲過程:
@SearchText VARCHAR(255)
AS
BEGIN
SET NOCOUNT ON;
SELECT RTRIM(NUID) NUID, RTRIM(FNAME) FNAME, RTRIM(LNAME) LNAME
FROM T_USER
WHERE NUID like @SearchText + '%' OR FNAME like @SearchText + '%' OR LNAME like @SearchText + '%'
謝謝!
很高興知道SP_我是如何受教的。我只是在我調用存儲過程之前添加您提供的代碼?另外,它似乎並不喜歡cmd.executeReader()行 – user1512593 2012-08-03 23:01:43
是的,把它放在你指定'CommandText'的位置,如果你給我錯誤從cmd.ExecuteReader我可以幫忙。它看起來像你兩次添加你的'@SearchText'參數。 – jtimperley 2012-08-03 23:10:50
你是對的! 「 」過程或函數SP_AUTOCOMPLETE指定的參數太多。「 – user1512593 2012-08-03 23:12:12