存储过程:
CREATE PROC Pro_GetNewsByTitleAndContentNumb
@newsKey VARCHAR(64),
@numb int out
AS
SELECT NewsTitle,SUBSTRING(NewsContent,1,20)+'......' as NewsContent,CreateTime FROM T_News
WHERE NewsTitle like @newsKey or NewsContent like @newsKey;
SELECT @numb=COUNT(*)FROM T_News
WHERE NewsTitle like @newsKey or NewsContent like @newsKey;
Go
前台代码:
<body>
<form id="form1" runat="server">
<div>标题:<asp:TextBox ID="txtNewsTitle" runat="server" ></asp:TextBox>
<asp:Button ID="btnQuery" runat="server" Text="搜索" onclick="btnQuery_Click" /> 共搜索到了<asp:Label
ID="Label1" runat="server" Text=""></asp:Label>条数据
<div id="divResult" runat="server">
</div>
</div>
</form>
</body>
后台代码:
string conStr = @"Data Source=.;Initial Catalog=News;Persist Security Info=True;User ID=sa;Password=111111";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataLoad();
}
}
private void DataLoad()
{
#region 根据用户的输入获取数据
SqlConnection conn = new SqlConnection(conStr);
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "Pro_GetNewsByTitleAndContentNumb";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@newsKey", "%" + txtNewsTitle.Text + "%");
#region output参数
SqlParameter param1 = new SqlParameter("@numb", SqlDbType.Int);
cmd.Parameters.Add(param1);
param1.Direction = ParameterDirection.Output;
#endregion
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
StringBuilder sb1 = new StringBuilder();
#endregion
#region 将数据拼接成字符串发送到前台
Label1.Text = (param1.Value).ToString();
string newscontent = string.Empty;
string newstitle = string.Empty;
sb1.Append("<table border=2");
sb1.Append("<tr><td>标题</td><td>内容</td><td>创建时间</td></tr>");
foreach (DataRow row in dt.Rows)
{
sb1.Append("<tr>");
newstitle = row["NewsTitle"].ToString();
sb1.Append("<td>" + newstitle + "</td>");
newscontent = row["NewsContent"].ToString();
sb1.Append("<td>" + newscontent + "</td>");
sb1.Append("<td>" + Convert.ToDateTime(row["CreateTime"].ToString()).ToString("yyyy-MM-dd hh-mm-ss") + "</td>");
sb1.Append("</tr>");
}
sb1.Append("</table>");
divResult.InnerHtml = sb1.ToString();
cmd.ExecuteNonQuery();
cmd.Dispose();
conn.Dispose();
#endregion
}
protected void btnQuery_Click(object sender, EventArgs e)
{
DataLoad();
}

本文展示了如何利用存储过程Pro_GetNewsByTitleAndContentNumb在SQL中搜索新闻标题和内容,并同时计算匹配的数据条数。在前端,用户输入搜索关键字,后台ASP.NET代码连接数据库执行存储过程,获取新闻标题、内容片段和创建时间,以及搜索结果的数量。搜索结果以表格形式展示给用户。

被折叠的 条评论
为什么被折叠?



