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

后端 未结 8 661
名媛妹妹
名媛妹妹 2020-12-07 12:12

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?

相关标签:
8条回答
  • 2020-12-07 12:40

    Try the following statement to check for existence of a table in the database:

    If not exists (select name from sysobjects where name = 'tablename')
    

    You may create the table inside the if block.

    0 讨论(0)
  • 2020-12-07 12:42
    Declare @Username varchar(20)
    Set @Username = 'Mike'
    
    if not exists 
    (Select * from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'tblEmp')
    
    Begin
        Create table tblEmp (ID int primary key, Name varchar(50))
        Print (@Username + ' Table created successfully')
    End
    
    Else
    
    Begin
        Print (@Username + ' : this Table Already exists in the database')
    End
    
    0 讨论(0)
提交回复
热议问题