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?
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.
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