Tuesday, April 23, 2013

Coldfusion inline cfquery (cfset like cfscript)

I'm a spotty blogger at best. I like to blog about fun discoveries, time-saving finds, success stories, solutions, or things that I don't find already being discussed in the Coldfusion railo community.

I had a fun find today. I don't code in CFSCRIPT. But I think it's fascinating. I prefer scripting languages but cfscript was so far behind the times for so long that I never thought it would be possible to write an entire application in cfscript. ...and I really dislike alternating between tag-coding and script-code in the same project. That is why I never embraced it. So I do a lot of short-hand one-off script-like things inside <cfset ... /> tags.

So I;ll share this one. Today I wanted a one-line statement to get a single value from the database, I have changed this code be able to hit mysql but not require any schema.

This is an inline query getting a single column. for some reason I really liked this.

<cfset variables.yearid = variables.qryRes = new Query().setSQL("select YEAR(NOW()) as yid").setDatasource(request.mydb).execute().getResult().yid />

Now, that's a long one-liner, but it did exactly what I was hoping to do in a single line. This is not possible with tag-coding. and it wouldn't be as practical with a complex query, but for a single value it skips all the multiple variables otherwise required for the query and the result and the new variable for the single value from the query column desired. This gets right down to business when the target is solo. And that simplicity won my heart.

I love one-liners!!!

Back to monotony of the daily grind.

See ya.

NOTE: the above code sample was run on Railo 4 with MySQL database.

No comments: