Friday, November 21, 2008    
Home My Books Blog ColdFusion About Me Back    

Calendar
<< Dec 2006 >>
S M T W T F S
          1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31            

Search

Categories
 • Acrobat (2) [RSS]
 • Adobe (71) [RSS]
 • AdobeMAX06 (45) [RSS]
 • AdobeMAX07 (59) [RSS]
 • AdobeMAX08 (46) [RSS]
 • AIR (144) [RSS]
 • Appearances (133) [RSS]
 • Books (69) [RSS]
 • CFEclipse (14) [RSS]
 • ColdFusion (1173) [RSS]
 • Data Services (16) [RSS]
 • Fish Tank (2) [RSS]
 • Flash (108) [RSS]
 • Flex (382) [RSS]
 • Home Automation (3) [RSS]
 • Jobs (100) [RSS]
 • JRun (13) [RSS]
 • Labs (29) [RSS]
 • LiveCycle (23) [RSS]
 • MAX (181) [RSS]
 • Regular Expressions (15) [RSS]
 • RIA (12) [RSS]
 • SQL (38) [RSS]
 • Stuff (505) [RSS]
 • Tips (CF Studio) (80) [RSS]
 • Tips (CF) (795) [RSS]
 • Tips (Dreamweaver) (91) [RSS]
 • Tips (Flex Builder) (2) [RSS]
 • Using CF (140) [RSS]
 • Wireless (100) [RSS]

Other BLOGs
 • Charlie Arehart
 • Lee Brimelow
 • Ray Camden
 • Christophe Coenraets
 • Sean Corfield
 • Mihai Corlan
 • Cornel Creanga
 • John Dowdell
 • Danny Dura
 • Enrique Duvos
 • Steven Erat
 • Kevin Hoyt
 • Serge Jespers
 • Adam Lehman
 • Duane Nickull
 • Miti Pricope
 • Andrew Shorten
 • Ryan Stewart
 • James Ward
 • Greg Wilson
 • Full As A Goog

RSS Feeds
 • Feed
 • Subscribe

Join my mailing list and find out about new books and other topics of interest.

Thoughts, ideas, tips, musings, and pontifications (not necessarily in that order) by Ben Forta ...
NOTE: This is my personal blog, and the opinions and statements voiced here are my own.

Viewing By Entry / Main
December 11, 2006

Dynamic SQL In SQL Server

We all rely on writing dynamic SQL in ColdFusion, but what if you need to write dynamic SQL on the server, perhaps in a stored procedure? While I'd not recommend overusing this technique (there are performance penalties to this one), if you need server-side dynamic SQL, the EXEC() function can help:

DECLARE @sql VARCHAR(100)
DECLARE @id INT

SET @id = 1234

SET @sql = 'SELECT * FROM MyTable'

IF @id <> ''
   SET @sql = @sql + ' WHERE id = ' + @id

EXEC(@sql)

It gets a little trickier if the WHERE clause needs to compare string values, then you need quotes around the value, and those quotes need to be escaped:

DECLARE @sql VARCHAR(100)
DECLARE @id VARCHAR(100)

SET @id = 'A1234'

SET @sql = 'SELECT * FROM MyTable'

IF @id <> ''
   SET @sql = @sql + ' WHERE id = ''' + @id + ''''

EXEC(@sql)

TrackBacks
There are no trackbacks for this entry.

No trackback URL. Trackbacks are only allowed via interactive form.

Comments
My understanding has always been that if you do this, the execution plan must be recompiled every time even though you are using a stored procedure, thus negating any performance benefit of using a sproc...plus (as you note) I have found a pretty decent performance hit when using this on anything more than simple statements.
# Posted By Brian Rinaldi | 12/11/06 8:03 PM
I'd pretty much only recommend doing this if a) there's no other choice, and b) the only values you're using in the dynamic statement are lookup up from data already in the DB, and don't consist of any user input. It's possible (though it takes a circumstance like bad use of preserveSingleQuotes()) to expose SQL injection points with this.

One place I have used this with good results is when the statement evaluated is name of another precompiled element, like dynamically choosing the name of a sproc to be invoked.
# Posted By Joe Rinehart | 12/11/06 9:17 PM
Brian and Joe, I agree. As I said, there is a real performance hit, and it's a last resort option. But, as it so happens, today I needed it - I have a realy complex query with even more complex WHERE clauses. I am working on a better solution, but for now (the hack to get it working until I figure it all out) this was the quick and dirty workable option.

--- Ben
# Posted By Ben Forta | 12/11/06 9:34 PM
Hey Ben,

I've been there :) I just wanted to make sure readers saw all side of it.

Is the query problem something you can share? Maybe we can all work on a different sol'n.
# Posted By Joe Rinehart | 12/12/06 7:49 AM
In Oracle same functionality is named EXECUTE_IMMEDIATE, obviously with same precautions as with SQL Server.

Tero
# Posted By Tero Pikala | 12/12/06 8:17 AM
Erland Sommarskog has an article titled "<a href="http://www.sommarskog.se/dyn-search.html">Dynamic Search Conditions in T-SQL</a>" that I found very helpful when I needed to write some dynamic SQL. He explains the different methods for writing dynamic SQL (EXEC() is not the only way, as I'm sure you know) and the tradeoffs of using them. Erland says that EXEC() is generally inferior to sp_executesql.
# Posted By Amy Adler | 12/12/06 8:50 AM
As with anything, there are exceptions to every rule. I use a stored proc that dynamically generates SQL statements I use for pagination.

http://blog.pengoworks.com/blogger/index.cfm?actio...

This allows me to pull out just specific "rows" from the query set. Since it uses the executesql stored proc, the query plan is cached and re-used. Performance of this stored proc is very good--better than any other SQL-based pagination solution I've found.
# Posted By Dan G. Switzer, II | 12/12/06 10:33 AM

  © Copyright 1997-2008 Ben Forta, All Rights Reserved