sqlsql-servert-sqlsql-server-2008-r2

Check if table exists and if it doesn't exist, create it in SQL Server 2008


I am writing a Stored procedure in SQL Server 2008. I need to check if a table exists in the database. If it doesn't then I need to create it.

How do I do this?


Solution

  • Something like this

    IF  NOT EXISTS (SELECT * FROM sys.objects 
    WHERE object_id = OBJECT_ID(N'[dbo].[YourTable]') AND type in (N'U'))
    
    BEGIN
    CREATE TABLE [dbo].[YourTable](
        ....
        ....
        ....
    ) 
    
    END