SQL Server:在用户定义函数中声明视图

时间:2014-09-03 19:00:10

标签: sql sql-server

我想在我的函数中创建视图,每当我想创建我的视图时,我只需要参考函数并调用它。

我写了这段代码但是我收到了一个错误:

create FUNCTION [dbo].[testFunc]()
RETURNS bigint
AS
BEGIN
    IF OBJECT_ID ('dbo.r_Sales01_Requests__Duplicates', 'V') IS NOT NULL
       DROP VIEW dbo.r_Sales01_Requests__Duplicates ;
    go

    create view r_Sales01_Requests__Duplicates ( 
     CompanyID
    ,Branch
    ,Year
    ,VoucherType,VoucherNumber
    ,Date_Persian
    ,Row) as
     select 
         CompanyID
        ,Branch
        ,Year
        ,VoucherType
        ,VoucherNumber
        ,Date_Persian
        ,Row
     from t_SalesRequests
     group by CompanyID, Branch, Year, VoucherType, VoucherNumber, Date_Persian, Row
     having count(*)>1

     return 
END

注意:在创建函数时,以下部分对我来说非常重要。

IF OBJECT_ID ('dbo.r_Sales01_Requests__Duplicates', 'V') IS NOT NULL
    DROP VIEW dbo.r_Sales01_Requests__Duplicates ;

1 个答案:

答案 0 :(得分:1)

功能不应该有副作用。您可以使用存储过程执行类似的操作:

Creating a View using stored procedure