Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
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: 1488 | Views in the last 30 days: 46
 
Related Articles
FORUM

Replacing strings

Replacing data

BLOG

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

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

ARTICLE

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

SCRIPT

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.

ARTICLE

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

Tags
dynamic sql    
parameters    
sp_executesql    
 
Contribute

Join the most active online SQL Server Community

SQL knowledge, delivered daily, free:

Email address:  

You make SSC a better place

As a member of SQLServerCentral, you get free access to loads of fresh content: thousands of articles and SQL scripts, a library of free eBooks, a weekly database news roundup, a great Q & A platform… And it’s our huge, buzzing community of SQL Server Professionals that makes it such a success.

Join us!

Steve Jones
Editor, SQLServerCentral.com

Already a member? Jump in:

Email address:   Password:   Remember me: Forgotten your password?
Steve Jones