Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server LIKE containing bracket characters

Using SQL Server 2008. I have a table with the following column:

sampleData (nvarchar(max)) 

The value for this column in some of these rows are lists formatted as follows:

["value1","value2","value3"] 

I'm trying to write a simple query that will return all rows with lists formatted like this, by just detecting the opening bracket.

SELECT * from sampleTable where sampleData like '[%' 

The above query doesn't work because '[' is a special character, and I can't for the life of me figure out how to escape the bracket so my query does what I want.

Thanks for any suggestions!

like image 411
CJS Avatar asked Sep 07 '10 17:09

CJS


People also ask

Why do you put [] in SQL?

Regardless of following a naming convention that avoids using reserved words, Microsoft does add new reserved words. Using brackets allows your code to be upgraded to a new SQL Server version, without first needing to edit Microsoft's newly reserved words out of your client code.

How do I find a bracket in SQL?

SQL: Finding square brackets using LIKE in SQL Server T-SQL The trick is that to find the opening bracket, you need to enclose it in a pair of square brackets. But you can just find the closing one directly. That returns no rows. That returns rows 1, 2, and 4 as expected.

How do I escape square brackets in SQL?

To escape square brackets in LIKE you can use another square bracket to escape the original square bracket or use a custom escape character using the ESCAPE keyword in LIKE clause.

What are [] for in SQL?

On SQL Server and MS Access, square brackets have a special meaning when used in a query filter. The square brackets are used to specify a set or range of characters, as in "[A-Z]" which would match any single character from 'A' to 'Z'.


1 Answers

 ... like '[[]%' 

You use [ ] to surround a special character (or range)

See the section "Using Wildcard Characters As Literals" in SQL Server LIKE

Edit, 24 Nov 2011

Note: You don't need to escape the closing bracket...

like image 164
gbn Avatar answered Oct 13 '22 17:10

gbn