SQL 服务器 : trying to create view inside a stored procedure

标签 sql sql-server tsql stored-procedures view

我试图在存储过程中创建我的 View ,但我遇到了一个错误。

我的代码是:

    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 

我遇到了这些错误:

Incorrect syntax near 'go'
'CREATE VIEW' must be the first statement in a query batch.
Maximum stored procedure, function, trigger, or view nesting level exceeded (limit 32).

最佳答案

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

我创建了以下程序来修改 View ,就像您所做的那样。除了不使用“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

关于SQL 服务器 : trying to create view inside a stored procedure,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25683455/

相关文章:

SQL:更新表,其中列 = 多个值

sql - 如何在 postgresql jsonb 搜索中使用 SIMILAR TO 子句获取不区分大小写的数据?

.net - SQL Server SMO 从远程服务器本地备份

c# - 由于引用 .net 程序集,无法创建程序集

sql - COUNT 选择和局部变量存储

SQL将日期时间的格式更改为特定样式

asp.net - 当我尝试从数据库中删除行时,出现参数过多错误

mysql - 在mysql中更新价格

sql - 这个 SQL 语句背后的含义是什么? ISNULL(状态,0) & 128 = 0?

sql-server - 将表从服务器1 DB“A”复制到服务器2 DB“B”的SQL Server T-SQL过程