reuse sql with view or function

前端 未结 4 532
说谎
说谎 2021-01-08 00:00

I have a sql query that I will be reusing in multiple stored procedures. The query works against multiple tables and returns an integer value based on 2 variables passed to

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-08 00:07

    You cannot pass variables into a view, so your only option it seems is to use a function. There are two options for this:

    • a SCALAR function
    • a TABLE-VALUED function (inline or multi-statement)

    If you were returning records, then you could use a WHERE clause from outside a not-too-complex VIEW which can get in-lined into the query within the view, but since all you are returning is a single column integer value, then a view won't work.

    An inline TVF can be expanded by the query optimizer to work together with the outer (calling) query, so it can be faster in most cases when compared to a SCALAR function.

    However, the usages are different - a SCALAR function returns a single value immediately

    select dbo.scalarme(col1, col2), other from ..
    

    whereas an inline-TVF requires you to either subquery it or CROSS APPLY against another table

    select (select value from dbo.tvf(col1, col2)), other from ..
    
    -- or
    
    select f.value, t.other
    from tbl t
    CROSS apply dbo.tvf(col1, col2) f   -- or outer apply
    

提交回复
热议问题