Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql select query using like

Tags:

c#

sql

I am trying to run this code

 public long getTopicCountWithTag(String tag)
    {
        long count;
        query = " SELECT count(*) FROM [DB_us2].[dbo].[discns] where tags like '%@tags%'";
        try
        {
            com = new SqlCommand(query, con);
            com.Parameters.AddWithValue("@tags", tag);
            con.Open();          
            sdr = com.ExecuteReader();
            sdr.Read();
            count= sdr.GetInt32(0);

        }
        catch (Exception e)
        {
            count = -1;
            throw e;
        }
        finally
        {
            con.Close();
        }
        return count;
    }

its giving output 0 . So i try figure out what is the problem and run sample query on management studio but output is different its giving 1. After trying all permutation combination, i think problem is with this statement com.Parameters.AddWithValue("@tags", tag); might be possible @tags is not replaced in query.

like image 372
Hot Cool Stud Avatar asked Oct 25 '13 07:10

Hot Cool Stud


People also ask

Can I use like in select SQL?

Description. The SQL LIKE condition allows you to use wildcards to perform pattern matching in a query. The LIKE condition is used in the WHERE clause of a SELECT, INSERT, UPDATE, or DELETE statement.

What is like %% in SQL?

The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. There are two wildcards often used in conjunction with the LIKE operator: The percent sign (%) represents zero, one, or multiple characters. The underscore sign (_) represents one, single character.

How use multiple values in SQL with like?

The SQL LIKE clause is used to compare a value to similar values using wildcard operators. There are two wildcards used in conjunction with the LIKE operator. The percent sign represents zero, one or multiple characters. The underscore represents a single number or character.

Is like filter in SQL?

You can use the LIKE operator in the WHERE condition to do a pattern matching comparison, like to find a string somewhere in a text value. The "%" character will match any sequence of 0 or more characters in the value, the "_" character will match a single character.


1 Answers

I think your query should be

string query = "SELECT count(*) FROM [DB_us2].[dbo].[discns] where tags like @tags";

And add the wildcard to the parameter

com.Parameters.AddWithValue("@tags", "%" + tag + "%");
like image 158
Kaf Avatar answered Oct 21 '22 20:10

Kaf