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

Prady picture Prady · May 10, 2011 · Viewed 394.6k times · Source

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?

Answer

SQLMenace picture SQLMenace · May 10, 2011

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