Search code examples
sqlcoldfusioncoldfusion-10cfquerysql-in

SQL IN - Variable inside of table column?


I know how to check for the value of a table column inside a variable list, like so:

<cfquery datasource="test_sql" name="get">
    Select a
    From b
    Where c In  
    (
        <cfqueryparam cfsqltype="cf_sql_varchar" list="true" value="#d#">
    )
</cfquery>

But how do I reverse the where clause? I've tried this which hasn't worked:

<cfquery datasource="test_sql" name="get">
    Select a
    From b
    Where <cfqueryparam cfsqltype="cf_sql_varchar" value="#c#"> In (d)
</cfquery>

This then looks for any match within the list stored in column d that has the value c.

Eg.

C = 12345

Column D - 4 Rows
12344,12345,12346 --- Match (List Item 2)
12323,12327,12375 --- No Match
12312,12341,12345 --- Match (List Item 3)
12128,12232,12345 --- Match (List Item 3)

The record count should then be 3 as there are a total of 3 matches where the value is present within the list. However, when I run this query it does not work.

I'd assume many people have stumbled upon this minor problem before and know the solution. Any help would be appreciated!


Solution

  • This query logic should work

    where d = <cfqueryparam cfsqltype="cf_sql_varchar" value="#c#"> 
    --- c is only element
    or d like <cfqueryparam cfsqltype="cf_sql_varchar" value="#c#,%"> 
    --- c is first element
    or d like <cfqueryparam cfsqltype="cf_sql_varchar" value="%,#c#,%"> 
    --- c is in the middle somewere
    or d like <cfqueryparam cfsqltype="cf_sql_varchar" value="%,#c#"> 
    --- c is last element