简体   繁体   English

在视图中执行存储过程?

[英]Execute stored procedure in a view?

Is it possible to execute a stored procedure in a view? 是否可以在视图中执行存储过程?

Ie

CREATE VIEW [dbo].[v_ReportInvoiceClientsThisMonth] AS EXEC [dbo].[GetInvoiceClients] @startDate = '2009-03-01', @endDate = '2009-04-01' 创建视图[dbo]。[v_ReportInvoiceClientsThisMonth]作为EXEC [dbo]。[GetInvoiceClients] @startDate ='2009-03-01',@endDate ='2009-04-01'

(doesn't work) (无效)

The reason I need this is that I need a way to access the SP in Excel (in an idiot safe way, ie without VBA). 我需要这样做的原因是,我需要一种在Excel中访问SP的方法(以一种傻瓜安全的方式,即没有VBA)。

You can do this with a view over a table-valued function. 您可以通过查看表值函数来执行此操作。 This looks something like: 看起来像这样:

-- === Table-Valued function ====================================
--
create function fn_foo (
       @Date datetime

) returns @ResultSet table (
        DateKey           datetime
       ,DisplayDate       varchar (20)
) as
    insert @ResultSet (
           DateKey
          ,DisplayDate
    )
    select DateKey      -- Just pretend there's something to select
          ,DisplayDate  -- behind the scenes
      from ods.Dates
     where DateKey <= @Date
    return
go


-- === View ============================================
-- 
create view vw_foo (
       DateKey
      ,DisplayDate
) as
select DateKey
      ,DisplayDate
  from fn_foo ('2009-04-31')
go

There are a few caveats: 有一些警告:

  • There are some limits to what you can do with functions. 函数的功能有一些限制。 In particular there is something of an impedance mismatch between stored procedure code and function code so you typically can't use a function to wrap around a stored procedure for the purposes of doing this sort of thing. 特别是在存储过程代码和函数代码之间存在某种阻抗不匹配的情况,因此,您通常不能使用函数来包装存储过程来进行此类操作。

  • The first point means you will probably have to re-cast your stored procedure as a table-valued function. 第一点意味着您可能必须将存储过程重新转换为表值函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM