Select with LIKE with argument%

2

I'm trying to make a select, using LIKE and setting the argument%:

  

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

source: link

However, when I run the direct command string in SQL Server Management Studio, it runs correctly, and when I try to run it, 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;
    }
    
asked by anonymous 14.08.2016 / 16:02

1 answer

5

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

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

and change the statement corresponding to like of your SQL query to:

like @codigo

instead of:

like '%@codigo%'
    
14.08.2016 / 16:33