Search code examples
sql-servert-sqlviewwhere-clauseopenquery

How to ensure specific WHERE condition evaluates first on view


Consider the following view:

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

When I run

select * from x where source=1

can I be sure that the select 2.... query is not even executed?

The reason is that in my case, that one is an openquery with sluggish speed, which I want to avoid.


Solution

  • You can do stuff like this, but i dont know if that meets your other requirements you might have - Otherwise you can create 2 views.

    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