条件FROM子句

时间:2014-04-15 12:58:01

标签: sql-server

我的同事正在使用实体框架,并且有3个(示意性)相同的数据库。这些数据库由其应用程序更新和修改。我正在编写另一个单独的应用程序来收集有关其应用程序的信息。

我正在尝试使用存储过程但遇到问题。看来我必须在每个存储过程中有三个查询副本(每个数据库一个),最后一个JOIN。我不希望每个查询都有三个副本,只更改了表名。我可以指定使用参数,CASE语句或我在FROM子句中使用的表吗?

2 个答案:

答案 0 :(得分:2)

两个选项:动态SQL或UNION ALL语句。

SELECT columnlist
FROM TABLE1
WHERE @param = 'Table1'
UNION ALL
SELECT columnlist
FROM TABLE2
WHERE @param = 'Table2'
UNION ALL
SELECT columnlist
FROM TABLE3
WHERE @param = 'Table3'

答案 1 :(得分:1)

由于您正在使用存储过程,因此可以将要查询的表名称作为参数传递,如

create procedure sp_test
@tab_name varchar(10)
as
begin
if(@tab_name = 'Table1')
select * from Table1
else if (@tab_name = 'Table2')
select * from Table2
else
select * from Table3
end

然后运行你的SP

exec sp_test 'Table1'

修改

根据您的评论,您要更改查询中的数据库名称。因此,在DB.HistoryOne JOIN DB.HistoryTwo中,您要将DB更改为DB1。您可以在以下过程中执行此操作

    create procedure sp_DB_change
    @DBname varchar(10)
    as
    begin      
   declare @sql varchar(200);
set @sql = 'SELECT AVG(DATEDIFF(s, StartDate, OtherStartDate)) AS time1 ,
CAST(OtherStartDate AS Date) AS [Date] 
FROM DB.HistoryOne 
JOIN DB.HistoryTwo ON HistoryOne.Id = HistoryTwo.Id 
WHERE StartDate IS NOT NULL 
AND OtherStartDate IS NOT NULL 
AND OtherStartDate > DATEADD(d, -7, GETDATE()) 
GROUP BY CAST(OtherStartDate AS DATE)';

select @sql = REPLACE(@sql,'DB',@newdb)
exec (@sql)
end

然后运行你的SP

exec sp_DB_change 'testDB'

所以你的原始查询

SELECT AVG(DATEDIFF(s, StartDate, OtherStartDate)) AS time1 ,
CAST(OtherStartDate AS Date) AS [Date] 
FROM DB.HistoryOne 
JOIN DB.HistoryTwo ON HistoryOne.Id = HistoryTwo.Id 
WHERE StartDate IS NOT NULL 
AND OtherStartDate IS NOT NULL 
AND OtherStartDate > DATEADD(d, -7, GETDATE()) 
GROUP BY CAST(OtherStartDate AS DATE)

将转换为

SELECT AVG(DATEDIFF(s, StartDate, OtherStartDate)) AS time1 ,
CAST(OtherStartDate AS Date) AS [Date] 
FROM testDB.HistoryOne 
JOIN testDB.HistoryTwo ON HistoryOne.Id = HistoryTwo.Id 
WHERE StartDate IS NOT NULL 
AND OtherStartDate IS NOT NULL 
AND OtherStartDate > DATEADD(d, -7, GETDATE()) 
GROUP BY CAST(OtherStartDate AS DATE)