sql server - Conditional FROM clause -
my coworkers using entity framework , have got 3 (schematically) identical databases. these databases updated , modified application. writing another, separate application gather information application.
i trying use stored procedures having trouble. seems must have 3 copies of query in every stored procedure (one each database) , join them @ end. don't want have 3 copies of every query table name changed. can specify using parameter, case statement, or else table use in clause?
since working stored procedures, can pass table name want query parameter like
create procedure sp_test @tab_name varchar(10) begin if(@tab_name = 'table1') select * table1 else if (@tab_name = 'table2') select * table2 else select * table3 end then run sp like
exec sp_test 'table1' edit:
as per comment want change db name in query. in db.historyone join db.historytwo want change db db1. can below in procedure
create procedure sp_db_change @dbname varchar(10) begin declare @sql varchar(200); set @sql = 'select avg(datediff(s, startdate, otherstartdate)) time1 , cast(otherstartdate date) [date] db.historyone join db.historytwo on historyone.id = historytwo.id startdate not null , otherstartdate not null , otherstartdate > dateadd(d, -7, getdate()) group cast(otherstartdate date)'; select @sql = replace(@sql,'db',@newdb) exec (@sql) end then run sp like
exec sp_db_change 'testdb' so original query
select avg(datediff(s, startdate, otherstartdate)) time1 , cast(otherstartdate date) [date] db.historyone join db.historytwo on historyone.id = historytwo.id startdate not null , otherstartdate not null , otherstartdate > dateadd(d, -7, getdate()) group cast(otherstartdate date) will converted to
select avg(datediff(s, startdate, otherstartdate)) time1 , cast(otherstartdate date) [date] testdb.historyone join testdb.historytwo on historyone.id = historytwo.id startdate not null , otherstartdate not null , otherstartdate > dateadd(d, -7, getdate()) group cast(otherstartdate date)
Comments
Post a Comment