Monday, August 18, 2008

Using CFQueryParam in Order By Clause

With all of the SQL Injection attacks going on in the ColdFusion world I thought that it may be beneficial to show everyone a way that I know of to have cfqueryparam'd 'Order By' clauses. If anyone knows of other ways to accomplish this, please feel free to post a comment on how to do so.

<cfquery name="GetData" datasource="#APPLICATION.DataSource#">
DECLARE @param varchar(25),
   @dataID varchar(25),
   @sql nvarchar(700);

SELECT @param=<cfqueryparam cfsqltype="cf_sql_varchar" value="#VARIABLES.orderby#">,
   @dataID=<cfqueryparam cfsqltype="cf_sql_varchar" value="#VARIABLES.DataID#">,
   @sql = 'SELECT ID,
   WHERE DataID = ' + @dataID + 'Order by ' + @param + ' asc';

EXEC sp_executesql @sql



  1. For myself, if I'm allowing a variable to be passed in for the ORDER BY in a SQL Statement, I typically will use a cfswitch and cfcase and just have a cfdefaultcase.

    <cfquery name="Products" datasource="#getDSN()#">

    SELECT ProductID, Title, Price, Rating

    FROM Products


    CategoryID=<cfqueryparam value='#url.categoryID#' cfsqltype="cf_sql_idstamp">


    <cfswitch expression="#url.sortBy#">

    <cfcase value="Price">Price</cfcase>

    <cfcase value="Title">Title</cfcase>

    <cfcase value="Rating">Rating</cfcase>




  2. I like the switch approach better.. depending on your database, using a bound variable will affect (or not affect) the query plan, producing a different outcome peformance wise than a static column

  3. Instead of a switch, I prefer:

    order by
    <cfif listFindNoCase("col1,col2,col3", url.sort)>

  4. This comment has been removed by the author.

  5. Thanks for the alternatives guys. I like the listfindnocase() approach better since it is the shortest. The beauty of the cfif and cfswitch methods is that you can also do the logic outside of the query if you do not like putting logic inside the cfquery block. Like...

    <cfif listFindNoCase("col1,col2,col3", url.sort)>
    <cfset VARIABLES.OrderBy = "ORDER BY #url.sort#">
    <cfset VARIABLES.OrderBy = "ORDER BY col1">

    <cfquery ...>
    SELECT *
    FROM table
    where 0 = 0
    </cfquery ...>

  6. Good hoot. Keep it up will visit your blog again for more valuable information’s…
    ColdFusion Developer

  7. This comment has been removed by a blog administrator.


Dyson AM09 Fan & Heater H2 Error

No idea what the actual error is and I couldn't find anything useful on the web, so hopefully this will help someone else. I assumed th...