如何确保特定的 WHERE 条件首先在视图中评估

How to ensure specific WHERE condition evaluates first on view

考虑以下观点:

create view x as
select 1 as [source],* from some_table
union all
select 2,* from some_other_table

当我运行

select * from x where source=1

我可以确定 select 2.... 查询甚至没有执行吗?

原因是在我的情况下,那个是速度慢的openquery,我想避免。

你可以做这样的事情,但我不知道这是否满足你可能有的其他要求 - 否则你可以创建 2 个视图。

CREATE proc dbo.usp_selectspecificquery 

@source int
AS

BEGIN

IF(@source = 1)
BEGIN

Select 1 as source, * from some_table

END
ELSE
Select 1 as source,* from some_table

union all
select 2 as source,* from some_other_table
END

exec dbo.usp_selectspecificquery 1