动态扩展SQL语句 - 页面搜索

时间:2010-09-09 16:00:22

标签: c# asp.net-mvc sql

在我的模型中,我有一个字符串txtSearche,其值来自文本框,如:

“你们好朋友”

如何为每个单词添加WHERE text LIKE '%Text%'动态添加动态语句?类似3次:

WHERE Text LIKE '%@Text%'";

这是我的代码:

string[] wordsFromTxtSearche = txtSearche.Split(' ');

SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = @"SELECT * "
                  + " FROM ForumThread "
                  + " WHERE Text LIKE '%@Text%'";
cmd.Parameters.Add(new SqlParameter("@Text", txtSearche));

我想我需要在For循环的帮助下完成它,但我不知道如何。请帮帮我

3 个答案:

答案 0 :(得分:3)

SQL不会在字符串中插入参数,您可以使用linq清理一些杂乱的循环代码。

string[] words = txtSearche.Split(' ', StringSplitOption.RemoveEmptyEntries);
string[] paramNames = Enumerable.Range(1, words.Length)
    .Select(i => "p" + i)
    .ToArray();
string likeClause = string.Join("AND ",
     paramNames.Select(name => "col like '%' + " + name + " + '%'");
SqlParmeter[] sqlParams = Enumerable.Range(1, words.Length)
    .Select(i => new SqlParameter(paramNames[i], words[i]))
    .ToArray();

SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = @"SELECT * FROM ForumThread WHERE " + likeClause;
cmd.Parameters.AddRange(sqlParams);

为了它的价值,请不要使用like来实施论坛搜索,而是使用full text search

答案 1 :(得分:1)

类似的东西:

string command = @"SELECT * FROM ForumThread where ";
bool first = false;

foreach (string word in words)
{
   if (first)
       command += " and ";
   else
       first = true;

   command += " Text like '%" + word + "%' ";
}

cmd.CommandText = command;

如果你想坚持参数,你必须创建一个方案来生成一个独特的参数,可能是这样的:

string command = @"SELECT * FROM ForumThread where ";
bool first = false;

for(int i = 0, len = words.Length; i < len; i++)
{
   string word = words[i];
   if (first)
       command += " and ";
   else
       first = true;

   command += " Text like @param" + i.ToString() + " ";
   cmd.Parameters.Add("@param" + i.ToString(), "%" + words[i] + "%");
}

cmd.CommandText = command;

HTH。

答案 2 :(得分:1)

看看这是否有效......完全未经测试:)

SqlCommand cmd = new SqlCommand(); 
cmd.Connection = connection; 
cmd.CommandType = System.Data.CommandType.Text; 
string sql = "SELECT * FROM ForumThread WHERE ";
// assuming you have at least 1 item always in wordsFromTxtSearche
int count = 1;
foreach (string word in wordsFromTxtSearche)
{
    if (count > 1) sql += " AND ";
    sql += "Text LIKE @Text" + count.ToString();
    cmd.Parameters.Add(new SqlParameter("@Text" + count.ToString(),
        string.Format("%{0}%", word)));
    count++;
}
cmd.CommandText = sql;