How can I check if a View exists in a Database?

前端 未结 10 1671
无人共我
无人共我 2021-01-31 07:00

I have some SQL code that needs to be executed if a certain View exists in a database. How would I go about checking if the View exists?

EDIT: The DBMS being used is Mic

相关标签:
10条回答
  • 2021-01-31 07:29

    This is the most portable, least intrusive way:

    select
        count(*)
    from
        INFORMATION_SCHEMA.VIEWS
    where
        table_name = 'MyView'
        and table_schema = 'MySchema'
    

    Edit: This does work on SQL Server, and it doesn't require you joining to sys.schemas to get the schema of the view. This is less important if everything is dbo, but if you're making good use of schemas, then you should keep that in mind.

    Each RDBMS has their own little way of checking metadata like this, but information_schema is actually ANSI, and I think Oracle and apparently SQLite are the only ones that don't support it in some fashion.

    0 讨论(0)
  • 2021-01-31 07:29
    if exists (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[MyTable]') )
    
    0 讨论(0)
  • 2021-01-31 07:29

    You can check the availability of the view in various ways

    FOR SQL SERVER

    use sys.objects

    IF EXISTS(
       SELECT 1
       FROM   sys.objects
       WHERE  OBJECT_ID = OBJECT_ID('[schemaName].[ViewName]')
              AND Type_Desc = 'VIEW'
    )
    BEGIN
        PRINT 'View Exists'
    END
    

    use sysobjects

    IF NOT EXISTS (
       SELECT 1
       FROM   sysobjects
       WHERE  NAME = '[schemaName].[ViewName]'
              AND xtype = 'V'
    )
    BEGIN
        PRINT 'View Exists'
    END
    

    use sys.views

    IF EXISTS (
       SELECT 1
       FROM sys.views
       WHERE OBJECT_ID = OBJECT_ID(N'[schemaName].[ViewName]')
    )
    BEGIN
        PRINT 'View Exists'
    END
    

    use INFORMATION_SCHEMA.VIEWS

    IF EXISTS (
       SELECT 1
       FROM   INFORMATION_SCHEMA.VIEWS
       WHERE  table_name = 'ViewName'
              AND table_schema = 'schemaName'
    )
    BEGIN
        PRINT 'View Exists'
    END
    

    use OBJECT_ID

    IF EXISTS(
       SELECT OBJECT_ID('ViewName', 'V')
    )
    BEGIN
        PRINT 'View Exists'
    END
    

    use sys.sql_modules

    IF EXISTS (
       SELECT 1
       FROM   sys.sql_modules
       WHERE  OBJECT_ID = OBJECT_ID('[schemaName].[ViewName]')
    )
    BEGIN
       PRINT 'View Exists'
    END
    
    0 讨论(0)
  • 2021-01-31 07:34

    IN SQL Server ,

    declare @ViewName nvarchar(20)='ViewNameExample'
    
    if exists(SELECT 1 from sys.objects where object_Id=object_Id(@ViewName) and Type_Desc='VIEW')
    begin
        -- Your SQL Code goes here ...
    
    end
    
    0 讨论(0)
提交回复
热议问题