Click here to Skip to main content
15,886,032 members
Articles / Database Development / SQL Server
Tip/Trick

SQL Synonyms :.: Avoiding Dynamic SQL

Rate me:
Please Sign up or sign in to vote.
4.63/5 (4 votes)
29 Oct 2013CPOL 16.4K   7   2
A first approach to avoid Dynamic SQL in stored procedures

Scenario

Multiple database scenario with the same structure, but different database name

Sometimes, we need to execute a stored procedure that manipulates table data, but don’t know which database will be, we usually pass it's name as a parameter, and fall into char concatenation and executing like the following:

SQL
declare @db varchar(10) = 'DatabaseName' -- This is a parameter actually.
declare @sentence varchar(max)
set @sentence = 'Insert into ' + @db + _
'.dbo.Table (Field1,Field2) Values (' + @Value1 + ',' + @Value2 + ') '

EXEC (@sentence)  

In complex scenarios of tables with multiple columns and datatypes, it is definitely annoying.

This is my first approach for a more elegant solution:

SQL
declare @db varchar(10) = 'DatabaseName' -- This is a parameter actually

EXEC ('CREATE SYNONYM synonym_Name  FOR ' +  @db  + '.dbo.Table')  

Insert into synonym_Name (Field1,Field2) Values (@Value1,@Value2)

DROP SYNONYM synonym_Name -- Apparently synonym can´t be updated.

Hope it helps someone.

Live long... and program!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
Argentina Argentina
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
SuggestionNot thread safe Pin
granadaCoder15-Mar-17 5:50
granadaCoder15-Mar-17 5:50 
I did some basic testing. Since the scope of the synonym is at the database level, this method is not thread-safe UNLESS you wrap the create synonym and all calls that use the synonym in a TRANsaction. I'm not "hatin'", I just want people to know in case they wholesale start implementing it. I love this track as a way around the despised dynamic sql. Thanks.
GeneralRe: Not thread safe Pin
Claudio cespon19-Aug-19 8:14
Claudio cespon19-Aug-19 8:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.