tsql - Dynamic SQL for multiple (common table) databases solution? -
i've been using dynamic sql query (in stored procedure) in order run single statement number of structured databases common tables.
for example:
solution 1:
alter proc [dbo].[example] @vc_db varchar(16) , @vc_example varchar(32) begin -- dummy query ssrs allow columns read in visual studio if 1 = 2 begin select t1.c1 , t1.c2 , t2.c3 , t2.c4 db1.dbo.t1 left join db1.dbo.t2 on t2.c1 = t1.c1 t2.c4 = @vc_example end -- dynamic query declare @vc_sql varchar(max) = ' select t1.c1 , t1.c2 , t2.c3 , t2.c4 ' + @vc_db + '.dbo.t1 left join ' + @vc_db + '.dbo.t2 on t2.c1 = t1.c1 t2.c4 = ''' + @vc_example + ''' ' print @vc_sql exec (@vc_sql) end
this has been working great far since allows pass additional parameters through whilst running statement/report multiple databases.
however, queries have grown far more complex, becoming difficult task both manage dummy query, converting standard sql dynamic format.
therefore, we've started looking other ways achieve this.
solution 2
our latest solution has been create view each common table (with addition of database column), in format:
alter view [dbo].[v_t1] select *, 'db1' db db1.t1 union select *, 'db2' db db2.t1 union select *, 'db3' db db3.t1
this has allowed write queries (within stored procedure) in simpler , easier fashion (no conversion "dynamic query" , no need dummy query picked visual studio), instead utilising additional database column limit , join data, such below:
select t1.c1 , t1.c2 , t2.c3 , t2.c4 v_t1 left join v_t2 on v_t2.c1 = v_t1.c1 , v_t2.db = v_t1.db -- join condition on database limit data v_t2.c4 = @vc_example , v_t1.db = @vc_db -- on database limit data
in addition, i've been able write stored procedure dynamically build these views inputting (common) table name, 1 rebuild these whenever new databases added.
we still unsure regarding efficiency/performance of 2 solutions above, although in cases solution 1 seems marginally quicker, solution 2 has been quicker on odd occasion. we're still further.
my question is.. can achieve in better way?
advance apologies, don't want discussion. i'd input whether knows easier , efficient way achieve above. many thanks.
Comments
Post a Comment