SQL Server:视图或函数包含自引用。视图或函数不能直接或间接引用自己

时间:2016-07-31 15:03:56

标签: sql-server

我试图通过执行ALTER VIEW声明来更改视图中存储的列的日期格式,但它不起作用,我不确定原因。< / p>

我的查询:

 ALTER VIEW v_cust_invoices
 AS
     SELECT 
         FORMAT(INV_DATE,'MM-dd-yy') as INV_DATE
     FROM 
         v_cust_invoices

我总是收到错误

  

查看或运行&#39; v_cust_invoices&#39;包含自我引用。视图或函数不能直接或间接引用自己

我尝试将INV_DATE的日期格式更改为mm-dd-yy(目前yy-mm-dd)。有人能帮我吗?不确定我做错了什么。

编辑:如果我这样做

 ALTER VIEW v_cust_invoices
 AS
     SELECT FORMAT(INV_DATE,'MM-dd-yy') as INV_DATE
     FROM INVOICE

相反,它会删除除INV_DATE以外的所有列。

查看定义:

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE VIEW [dbo].[v_cust_invoices] AS 
    SELECT 
        CUSTOMER.CUST_NUM, CUST_LNAME,
        CUST_BALANCE, INV_NUM, INV_DATE, INV_AMOUNT 
    FROM 
        CUSTOMER, INVOICE
GO

1 个答案:

答案 0 :(得分:2)

您必须更改查询,使其不引用自身 在v_cust_invoices子句中查看FROM视图的当前定义。您将看到对表或其他视图的引用。将查询中的最后一行替换为下面的最后一行,替换该表(或其他视图)的名称,该视图从中获取数据。

ALTER VIEW v_cust_invoices
AS
SELECT FORMAT(INV_DATE,'MM-dd-yy') as INV_DATE, 
    [Plus all the rest of the output columns 
     from CURRENT definition of v_cust_invoices]
FROM [here Put the table or other view that is in current view definition]

或者,现在op发布了完整的视图定义:

ALTER VIEW [dbo].[v_cust_invoices] AS 
  SELECT FORMAT(INV_DATE,'MM-dd-yy') INV_DATE, 
       CUSTOMER.CUST_NUM, CUST_LNAME,
       CUST_BALANCE, INV_NUM, INV_DTE, INV_AMOUNT 
  FROM CUSTOMER, INVOICE
GO