【问题标题】:How to search a word inside a string where word is in a SQL Server table如何在字符串中搜索单词在 SQL Server 表中的单词
【发布时间】:2016-03-06 13:57:11
【问题描述】:

我有一个包含两列 KeywordEmotion 的 SQL Server 表。

我想在包含句子的字符串中搜索一个单词(在列Keyword 中指定)。例如:- 你好吗

我要执行两个查询:

  1. 我想搜索字符串是否包含“how”(howKeyword 列中指定)..

  2. 如果字符串中包含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)**//
        }
    }
}

【问题讨论】:

  • 我不明白你为什么需要两个查询,你有一个就足够了。
  • 我的意思是说我想要执行两个操作,即搜索一个单词并获取相应的值
  • 嗯,这就是半 sql 的作用......所以......我没有得到你的问题或问题。
  • 我提供的代码不起作用它给出了 sql 异常.. 所以我想修复这个代码
  • 好的,那么,错误是什么?生成的完整 sql 是什么?

标签: c# sql .net sql-server database


【解决方案1】:

您只需要一个 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 + "%";

【讨论】:

  • 我不想在关键字旁边提及“如何”,正如您所展示的那样。只是指向包含数百个单词的列的直接链接,其中一个可以是“如何”
  • 它给了我这个错误--->不能在表或索引视图“消息分析”上使用 CONTAINS 或 FREETEXT 谓词,因为它不是全文索引。
  • 我不确定我是否能理解你的问题,我已经编辑了我的答案以使用参数化查询,希望这对你有用。
  • 两种方法都不起作用..它必须声明标量变量@searchparam
猜你喜欢
  • 2022-01-02
  • 1970-01-01
  • 1970-01-01
  • 2011-12-27
  • 2010-09-14
  • 2016-04-26
  • 1970-01-01
相关资源
最近更新 更多