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)
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.
--- 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.
Tero
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.