0

我们正在做这样的事情

create view v1 
as 
select 'tab1' as table_name , * from table1
union All
select 'tab2' as table_name , * from table2
union All
select 'tab3' as table_name , * from table3

然后在一个SP中,

declare @var = function_gettablename()
    select * from v1 where table_name = @var and datetoload = <ActualDate>

function_gettablename() = gives the table name based on parameters

datetoload = 在所有表上互斥的非聚集索引列。即一个日期将仅在一张表中可用

现在的问题是在执行计划中:使用@var 使视图查询所有三个表,而不是所需的一个。

有没有办法应用过滤器然后应用联合所有,而不是运行联合所有然后应用过滤器。

谢谢 AB

4

1 回答 1

0

请检查这个-:

DECLARE @Var VARCHAR(MAX)
SET @Var = function_gettablename()
DECLARE @Sql VARCHAR(MAX)
DECLARE @ActualDate DATETIME
SET @ActualDate ='2013/2/14'

SET @sql = 'SELECT tab1 as '+@Var+' , * FROM table1 
            WHERE dateload ='+@ActualDate+ ' UNION ALL
            SELECT tab2 as '+@Var+' , * FROM table1 
            WHERE dateload ='+@ActualDate+' UNION ALL
            SELECT tab3 as '+@Var+',* FROM table1 
            WHERE dateload ='+@ActualDate

Exec(@Sql)
于 2013-02-14T07:20:19.483 回答