Random SQL Server results - a one word command

I learned a great way to randomize SQL results.

In the past, I would have followed this routine:

Run a query pulling all of the results (tens? hundreds? thousands?).
Create an array.
Loop until 5 good random results are made:
    Get 1 random query result.
    If it's not in the array, put it in.
    If it is in the array, ignore it and try again.
Then I'd output the data from the array, rather than the query.

I suppose I could simply fill an array then randomize it. But that's not really the point.

As you see, with this version we have to pull back so many more results than we're actually going to use. That's wasteful - especially if you want to pull back lots of data in each row.

So what's this great super duper new way I've discovered to simplify code, only pull back the 5 results from SQL Server, and run fast? It's really simple: tell SQL Server to do the work for you, with one word. No post parsing needed!

» Continue Reading »

Pagination with ColdFusion and MSSQL (faux MySQL's LIMIT X,Y)

Pagination is something that has always been somewhat difficult for me. Especially optimizing it for large sites. To make it even harder, the customer wants the first page to show three items, and every subsequent page to show ten. Not hard enough? OK, they want page number links instead of simple left/right arrow links, such as:

1 2 3 [4] Next »

Still Easy?

  • Only show 4 page links at a time
  • When you click 'next', show the next block of 4 pages
  • When you click 'prev', show the previous block of 4 pages
  • If you are on the first block of links, do not show the 'prev' link
  • If you run out of records, only show the correct number of page links in that block
  • If you run out of records, do not show the 'next' link

Remember, page 1 has 3 items. Page 2 has 10. So the math gets kinda tricky when you don't want to do 'what page are we on' statements all over the place.

Here is my solution. All you have to do is enter your records per page ("allperpage"), number of page links at a time ("blocksof"), and the number of items on the first page ("firstperpage").

The SQL query has been optimized to get as close to MySQL's 'LIMIT' function as possible. We're doing an INNER JOIN here, and sorting on columns from both tables. I haven't seen any examples of this optimization technique with an inner join, or even sorting on more than one column. We pull back the max rows we'd need, then trim the top with a reverse sort, finally un-reverse the sort for the web page. WHEW.

Onto the code...

» Continue Reading »

BlogCFC was created by Raymond Camden. This blog is running version 5.6.001.