Select with LIKE argument %

Asked

Viewed 2,011 times

2

I’m trying to perform a select, using LIKE and defining the argument %:

WHERE title LIKE '%computer%' locates all book titles with the word 'computer' anywhere in the book title.

source: https://msdn.microsoft.com/pt-br/library/ms179859.aspx

However, when I run the direct command string in SQL Server Management Studio, it runs straight, and when I try to run via program, it returns me blank.

Code SELECT:

    public DataTable Qgrid_estoque_cod_tipo_1(int tipo, int tipo1, string codigo, int inicio, int fim)
    {
        conexao.bd_string();

        SqlConnection sqlconn = new SqlConnection(conexao.sqlconn);

        DataTable grid_produtos = new DataTable();

        try
        {
            conexao._sql = @"SELECT b.descricao AS TIPO, a.familia AS FAMILIA, a.sub_familia AS 'SUB FAMILIA', a.codigo AS CÓDIGO, a.descricao AS DESCRIÇÃO, a.etq_un AS UNIDADE, a.bloq, a.etq_loc AS LOCALIZAÇÃO
                             FROM Estoque AS a
                             LEFT JOIN Tipos_estoque AS b
                             ON a.tipo = b.tipo
                             WHERE a.tipo = @tipo AND a.codigo LIKE '%@codigo%' AND a.id BETWEEN @inicio AND @fim OR a.tipo = @tipo1 AND a.codigo LIKE '%@codigo%' AND a.id BETWEEN @inicio AND @fim";

            SqlCommand cmd = new SqlCommand(conexao._sql, sqlconn);

            cmd.Parameters.Add("@tipo", SqlDbType.VarChar).Value = tipo;
            cmd.Parameters.Add("@tipo1", SqlDbType.VarChar).Value = tipo1;
            cmd.Parameters.Add("@codigo", SqlDbType.VarChar).Value = codigo;
            cmd.Parameters.Add("@inicio", SqlDbType.VarChar).Value = inicio;
            cmd.Parameters.Add("@fim", SqlDbType.VarChar).Value = fim;

            sqlconn.Open();

            cmd.CommandType = CommandType.Text;

            SqlDataAdapter da = new SqlDataAdapter(cmd);

            da.Fill(grid_produtos);
        }
        catch
        {

        }
        finally
        {
            sqlconn.Close();
        }

        return grid_produtos;
    }
  • 1

    Try to use the method AddWithValue in this way cmd.Parameters.AddWithValue("@codigo", "%" + codigo + "%"); this way I believe q will work.

  • 1

    Vc tbm will have to change the query to like @codigo instead of like '%@codigo%'

  • Perfect, thank you very much, please if you can answer the question, to put as answered thank you very much

1 answer

5


Use the method AddWithValue to pass the value to the parameter @codigo in this way:

cmd.Parameters.AddWithValue("@codigo", "%" + codigo + "%");

and change the instruction corresponding to the like from your SQL query to:

like @codigo

instead of:

like '%@codigo%'

Browser other questions tagged

You are not signed in. Login or sign up in order to post.