Check if table exists in SQL Server

前端 未结 28 2073
梦如初夏
梦如初夏 2020-11-22 04:23

I would like this to be the ultimate discussion on how to check if a table exists in SQL Server 2000/2005 using SQL Statements.

When you Google for the answer, you g

28条回答
  •  野的像风
    2020-11-22 04:47

    i taking here creating a view as example.

    Because ALTER/CREATE commands can't be within BEGIN/END blocks. You need to test for existence and the drop it before doing a create

    IF Object_ID('TestView') IS NOT NULL
    DROP VIEW TestView
    
    GO
    
    CREATE VIEW TestView
       as
       . . .
    
    GO
    

    If you are woried about the permissions being lost you can script the GRANT statements as well and re-run those at the end.

    You could wrap the create/alter into a string and do an EXEC - that might get ugly for large views

    DECLARE @SQL as varchar(4000)
    
    -- set to body of view
    SET @SQL = 'SELECT X, Y, Z FROM TABLE' 
    
    IF Object_ID('TestView') IS NULL
        SET @SQL = 'CREATE VIEW TestView AS ' + @SQL
    ELSE    
        SET @SQL = 'ALTER VIEW TestView AS ' + @SQL
    

提交回复
热议问题