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

前端 未结 10 1670
无人共我
无人共我 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:08

    if it's Oracle you would use the "all_views" table.

    It really depends on your dbms.

    0 讨论(0)
  • 2021-01-31 07:08

    To expand on Kevin's answer.

        private bool CustomViewExists(string viewName)
        {
            using (SalesPad.Data.DataConnection dc = yourconnection)
            {
                System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(String.Format(@"IF EXISTS(select * FROM sys.views where name = '{0}')
                    Select 1
                else
                    Select 0", viewName));
                cmd.CommandType = CommandType.Text;
                return Convert.ToBoolean(dc.ExecuteScalar(cmd));
            }
        }
    
    0 讨论(0)
  • 2021-01-31 07:16

    If you want to check the validity and consistency of all the existing views you can use the following query

    declare @viewName sysname
    declare @cmd sysname
    DECLARE check_cursor CURSOR FOR 
    SELECT cast('['+SCHEMA_NAME(schema_id)+'].['+name+']' as sysname) AS viewname
    FROM sys.views
    
    OPEN check_cursor
    FETCH NEXT FROM check_cursor 
    INTO @viewName
    
    WHILE @@FETCH_STATUS = 0
    BEGIN
    
    set @cmd='select * from '+@viewName
    begin try
    exec (@cmd)
    end try
    begin catch
    print 'Error: The view '+@viewName+' is corrupted .'
    end catch
    FETCH NEXT FROM check_cursor 
    INTO @viewName
    END 
    CLOSE check_cursor;
    DEALLOCATE check_cursor;
    
    0 讨论(0)
  • 2021-01-31 07:22

    FOR SQL SERVER

    IF EXISTS(select * FROM sys.views where name = '')
    
    0 讨论(0)
  • 2021-01-31 07:25

    There are already many ways specified above but one of my favourite is missing..

    GO
    IF OBJECT_ID('nView', 'V') IS NOT NULL
        DROP VIEW nView;
    GO
    

    WHERE nView is the name of view

    UPDATE 2017-03-25: as @hanesjw suggested to drop a Store Procedure use P instead of V as the second argument of OBJECT_ID

    GO
    IF OBJECT_ID( 'nProcedure', 'P' ) IS NOT NULL 
        DROP PROCEDURE dbo.sprocName; 
    GO
    
    0 讨论(0)
  • 2021-01-31 07:27

    For people checking the existence to drop View use this

    From SQL Server 2016 CTP3 you can use new DIE statements instead of big IF wrappers

    syntax

    DROP VIEW [ IF EXISTS ] [ schema_name . ] view_name [ ...,n ] [ ; ]

    Query :

    DROP VIEW IF EXISTS view_name
    

    More info here

    0 讨论(0)
提交回复
热议问题