Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Like Statement in SQL

I've been racking my brain on how to do this for a while, and i know that some genius on this site will have the answer. Basically i'm trying to do this:

SELECT column 
  FROM table 
 WHERE [table].[column] LIKE string1 
       OR [table].[column] LIKE string2 
       OR [table].[column] LIKE string3...

for a list of search strings stored in a column of a table. Obviously I can't do a like statement for each string by hand because i want the table to be dynamic.

Any suggestions would be great. :D

EDIT:

I'm using MSSQL :(

like image 379
Derwent Avatar asked Jan 06 '11 06:01

Derwent


People also ask

What is a dynamic SQL statement?

Dynamic SQL is a programming technique that enables you to build SQL statements dynamically at runtime. You can create more general purpose, flexible applications by using dynamic SQL because the full text of a SQL statement may be unknown at compilation.

Can I use CTE in dynamic SQL?

Using CTEs, for instance, you can use SELECT from <subquery> in Open SQL. In my case I needed to execute dynamic SELECT count( DISTINCT col1, col2, …) which is not possible in the regular OpenSQL.


1 Answers

Put the parameters (string1, string2, string3...) into a table (Params) then JOIN to the table using LIKE the JOIN clause e.g.

SELECT column 
  FROM table AS T1
       INNER JOIN Params AS P1
          ON T1.column LIKE '%' + P1.param + '%';
like image 90
onedaywhen Avatar answered Oct 14 '22 02:10

onedaywhen