小编典典

SQL Server:尝试在存储过程内创建视图

sql

我试图在存储过程中创建视图,但遇到错误。

我的代码是:

    alter PROCEDURE p.Azmoon1 
    AS
    begin
       EXEC ('IF OBJECT_ID (''r.r_Sales01_Requests__Duplicates'', ''V'') IS NOT NULL
            DROP VIEW r.r_Sales01_Requests__Duplicates ;
            go
            create view r.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

        go

    ')
    end

当我如下调用我的过程时:

execute p.Azmoon1

我收到这些错误:

‘go’附近的语法不正确
‘CREATE VIEW’必须是查询批处理中的第一条语句。
超出最大存储过程,函数,触发器或视图嵌套级别(限制32)。


阅读 162

收藏
2021-04-14

共1个答案

小编典典

正确删除@mark_s中提到的“ Go”,它不是EXEC中可执行的SQL关键字。

我创建了以下过程来像您一样修改视图。除了使用“ Go”之外,我使用了两个单独的EXEC语句。

create procedure [dbo].[CreateInvoiceView]
as 
begin
    Exec ('If object_ID(''invoices'',''V'') is not null 
            drop view invoices;')

    Exec ('
        create view [dbo].[Invoices] AS
           SELECT Orders.ShipName as SHIP_Name, Orders.ShipAddress, Orders.ShipCity, Orders.ShipRegion, Orders.ShipPostalCode,Orders.ShipCountry, Orders.CustomerID, Customers.CompanyName AS CustomerName, Customers.Address, Customers.City, Customers.Region, Customers.PostalCode, Customers.Country, (FirstName + '' '' + LastName) AS Salesperson, Orders.OrderID, Orders.OrderDate, Orders.RequiredDate, Orders.ShippedDate, Shippers.CompanyName As ShipperName
            FROM    Shippers INNER JOIN 
                    (Products INNER JOIN 
                       (
                       (Employees INNER JOIN 
                       (Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID) 
                              ON Employees.EmployeeID = Orders.EmployeeID) 
                              INNER JOIN "Order Details" ON Orders.OrderID = "Order Details".OrderID) 
                              ON Products.ProductID = "Order Details".ProductID) 
                              ON Shippers.ShipperID = Orders.ShipVia

    ')
end
2021-04-14