Skip to main content
Participating Frequently
April 23, 2007
Question

SQL IN statement

  • April 23, 2007
  • 6 replies
  • 953 views
Hi,

I'm trying to run a query that looks something like this

<cfquery name="test" datasource = "ds1">
SELECT *
FROM tblTest
WHERE '#variables.test#' IN (txCommaDelimitedList)
</cfquery>

where variables.test is an integer and txCommaDelimitedList is a database field like '100','101','102'. This doesnt work though. Any ideas?
This topic has been closed for replies.

6 replies

Inspiring
April 23, 2007
I can see a few obvious problems with the SQL:

1) You should not use quotes surrounding #variables.test#. The resulting SQL should be:

WHERE myCol IN (myList)

and not
WHERE 'myCol' IN (myList)

2) You don't have txCommaDelimitedList surrounded by pound signs, so CF is treating it as the literal text: "txCommaDelimitedList". Look into using <cfqueryparam> you can use the list="Yes" parameter to handle comma delimited lists (even integers).

WHERE #Variables["test"]# IN (<cfqueryparam cfsqltype="CF_SQL_INTEGER" value="#txCommaDelimitedList#" list="Yes">)

3) Using a CF variable like that in your query statement is incredibly insecure. You're pretty much setting yourself up for a SQL injection attack. You might look into using a switch/case statement, or at least performing an initial query to make sure that Variables.test is a valid column name and not something like:

1=1;
DROP TABLE
SELECT * from SomeTable WHERE 1
fshinAuthor
Participating Frequently
April 23, 2007
bc txCommaDelimitedList is a varchar field since it has the commas in sql
Participating Frequently
April 23, 2007
so which one is your field, and which one is your set of values? You can NOT do this:

SELECT something
FROM table
WHERE 'value' IN (COLUMN_name1, COLUMN_Name2, etc.)

This is invalid SQL!

Should be more like

WHERE COLUMN_Name IN('value','value','etc.')

Phil
Participating Frequently
April 23, 2007
Why is variables.test in quotes?
Participating Frequently
April 23, 2007
Whats the error you get?
Inspiring
April 23, 2007
You'd need to loop over variables.test and create dynamic statement.

<cfset tempSQLStatement ="WHERE #listFirst(variables.test)# IN (txCommaDelimitedList)" />

<cfloop list="#listRest(variables.test)#" index="i">
<!--- you could also use OR --->
<cfset tempSQLStatement = "AND #i# IN (txCommaDelimitedList)" />

</cfloop>

<cfquery name="test" datasource = "ds1">
SELECT *
FROM tblTest
#tempSQLStatement#
</cfquery>
Inspiring
April 23, 2007
Normalize your database and you won't have problems like this.
fshinAuthor
Participating Frequently
April 23, 2007
Actually, my example was bad. It should have read:

SELECT *
FROM view_test
WHERE '#variables.test#' IN (txCommaDelimitedList)

It's a view where txCommaDelimitedList is a field which contains a comma delimited list of integers based on the results of a query of an xref table.

No errors. Just no results.