CREATE TABLE IF NOT EXISTS works on mysql but fails with SQL Server 2008 R2.
What is the equivalent syntax?
1 Answer
if not exists (select * from sysobjects where name='cars' and xtype='U')
create table cars (
Name varchar(64) not null
)
go
The above will create a table called cars if the table does not already exist.
4 Comments
marc_s
Better yet - use the specific
sys.tables catalog view instead of having to remember what obscure xtype a table is...Neil Knight
@marc_s: Yes. Another good way :o) In fact, probably a better way.
bart
Since this is the top question for this topic in Google even though it has been closed:
if not exists (select * from sys.tables t join sys.schemas s on (t.schema_id = s.schema_id) where s.name = 'myschema' and t.name = 'cars') create table myschema.cars ( Name varchar(64) not null )crucifery
Coming back to this in 2017:
IF OBJECT_ID(N'dbo.Cars', N'U') IS NULL BEGIN CREATE TABLE dbo.Cars (Name varchar(64) not null); END;
GOafter create, we cannot put the create command insideBEGINandENDblock, as the answer for other question suggests.Ywhen they’re actually askingX(whereas in the XY problem the asker asksYwhen they’re trying to solveX). I.e., the asker did the right thing and the question is closed? sad face