SQL Clone
SQLServerCentral is supported by Redgate
Log in  ::  Register  ::  Not logged in

Get your favorite SSC scripts directly in SSMS with the free SQL Scripts addin. Search for scripts directly from SSMS, and instantly access any saved scripts in your SSC briefcase from the favorites tab.
Download now (direct download link)

Hassle free parameters in dynamic SQL

By Peter Sloboda,

I don't know about you, but passing parameters to sp_executesql via variables was never my favorite (I'm sorry if it was/is yours).

The above script offers a dynamic keyword replacement in a query string, by storing the keyword-value pairs in a @keywords table (for one-time use, which can be changed to permanent table for re-use).

The @sql string represents a simple select from the temporary table created on top.

The placeholders in the @sql string are delimited by '<%' and '%>' and are replaced by values in the @keywords table by matching the keyword with the placeholders:

select @sql=replace(@sql,'<%'+keyword+'%>',value) from @keywords...

Besides the fact that the keywords can be stored permanently and reused, I find it pretty cool that there is no need to iterate over the @sql string to replace all the placeholders. 

Total article views: 4028 | Views in the last 30 days: 1
Related Articles

Replacing strings

Replacing data


"Failover Partner" keyword in connection string - Q&A

1. How to connect client to a Database Mirroring Session with failover aware A: add FailoverPartn...


Tame Those Strings! Part 3 - Using REPLACE

The third part of Steve Jones's series on programming and manipulating strings in T-SQL dealing with...


Find and Replace a String in the Whole Database

Find and Replace a string in all string fields (char, varchar, etc) of all tables in the database.


TSQL Challenge 34-Search for two keywords within the maximum distance

This challenge is all about searching for two keywords in a string with a maximum distance of 'one w...

dynamic sql