无效的对象名称' view3' - 如何在SQL Server中访问视图?

时间:2014-08-16 20:19:54

标签: sql-server

create view view3 as
(
    select distinct 
        tblDivingClub.number as divingClub,
        (select count(*) 
         from tblAuthorized 
         WHERE tblAuthorized.club_number = tblDivingClub.number 
           and tblAuthorized.authorization_date <= DATEADD(month,-1, GETDATE())) as levels, 
        (select count(*) 
         from tblDiving 
         WHERE tblDiving.diving_club=tblDivingClub.number 
           and tblDiving.date_of_diving <= DATEADD(month,-1, GETDATE())) as divings
    from 
       tblDiving, tblDivingClub, tblAuthorized
)
go

create view view2 as
(
    select 
       divingClub
    from 
       view3
)
go

当我尝试根据view2创建view3时,SQL Server无法识别view3。我收到此错误:

  

无效的对象名称&#39; view3&#39;

如何访问view3

1 个答案:

答案 0 :(得分:1)

我在我的一个数据库中尝试了类似的场景,并且这样它应该可以工作(括号在SQL Server 2008 R2上给了我错误,否则看起来很好)

CREATE VIEW view3
AS
        SELECT DISTINCT tblDivingClub.number AS divingClub
            ,(
                SELECT count(*)
                FROM tblAuthorized
                WHERE tblAuthorized.club_number = tblDivingClub.number
                    AND tblAuthorized.authorization_date <= DATEADD(month, - 1, GETDATE())
                ) AS levels
            ,(
                SELECT count(*)
                FROM tblDiving
                WHERE tblDiving.diving_club = tblDivingClub.number
                    AND tblDiving.date_of_diving <= DATEADD(month, - 1, GETDATE())
                ) AS divings
        FROM tblDiving
            ,tblDivingClub
            ,tblAuthorized

GO

CREATE VIEW view2
AS
    SELECT divingClub
    FROM view3
GO 

SELECT * FROM VIEW2