Search code examples
t-sqlwildcardspacesql-like

tsql using like with wildcard and trailing space?


I cannot get the like statement to work with space and trailing wildcard. My query goes as follows:

select * from Table where Field like 'Desc_%'

The data is space-delimited such as, Desc Top, Desc Bottom and so on. The query works when I use the pattern 'Desc_%' but not when I use the pattern 'Desc %'. The field is nvarchar(255).

Any ideas?

EDIT

Turns out the data was tab-delimited and when I copied a value from the 2008 Management Studio it converted the tab to space. Dumb mistake. I did like the [ ] tip so I marked it the answer. Thanks everyone, I'll remember not to trust the copy from the grid results.


Solution

  • Use brackets '[' & ']' to set up a single-character class to match. In your case the SQL should look like this: "select * from Table where Field like 'Desc[ ]%'"

    EDIT: add sample, link

    CREATE TABLE #findtest (mytext  varchar(200) )
    
    insert #findtest VALUES ('Desc r')
    insert #findtest VALUES ('Descr')
    
    select * from #findtest where mytext like 'Desc[ ]%'
    
    DROP TABLE #findtest
    
    (1 row(s) affected)
    
    (1 row(s) affected)
    mytext
    --------
    Desc r
    
    (1 row(s) affected)
    

    See this article.