Select with like with argument %

I am trying to perform a select, using LIKE and setting 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 execute the direct command string in SQL Server Management Studio, it executes right, and when I try to execute via Program, the same 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;
    }
Author: Thomas Erich Pimentel, 2016-08-14

1 answers

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%'
 5
Author: gato, 2016-08-14 14:33:09