我有一个SQL Server表,其中包含两列Keyword
和Emotion
。
我想在包含句子的字符串中搜索一个单词(在Keyword
列中指定)...例如: - 你好吗
我想执行两个查询:
我想搜索字符串是否包含"如何" (how
列)中指定了Keyword
..
如果字符串包含how
,我想显示存储在表格Emotion
列中的相应值
这是我的示例代码(可能完全错误:p): -
public partial class message : System.Web.UI.Page
{
string constring = ConfigurationManager.ConnectionStrings["AnonymiousSocialNetworkConnectionString"].ToString();
protected void btnsend_Click(object sender, ImageClickEventArgs e)
{
SqlConnection con = new SqlConnection(constring);
string value = txtmsg.Text;
con.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select emotion from messageanalysis where keyword CONTAINS'",con);
myReader = myCommand.ExecuteReader();
while(myReader.Read())
{
lblStatus.Text = myReader["emotion"].ToString();// **this label should Display corresponding value stored in Emotion(column)**//
}
}
}
答案 0 :(得分:0)
您只需要一个SQL命令,它应该如下所示 -
string searchParam = "hello";
SqlCommand myCommand = new SqlCommand("select emotion from messageanalysis where CONTAINS(keyword,@SearchParam)",con);
myCommand.Parameters.Add("@SearchParam", System.Data.SqlDbType.VarChar, 20).Value = searchParam,;
如果服务器上未启用全文功能,CONTAINS可能无效。请查看此链接了解更多详情 - Cannot use a CONTAINS or FREETEXT predicate on table or indexed view because it is not full-text indexed
如果您不想启用此功能,请使用LIKE -
SqlCommand myCommand = new SqlCommand("select emotion from messageanalysis where keyword like @SearchParam)",con);
myCommand.Parameters.Add("@SearchParam", System.Data.SqlDbType.VarChar, 20).Value = "%" + searchParam + "%";