I need to check if a table in SQL exist or not.
If not it must create one automatically.
Now I researched and found this code:
IF NOT EXISTS (SE
The ISO SQL way to check existence of a table level object is the INFORMATION_SCHEMA.TABLES view
There's nothing wrong with looking at sys.objects but.... INFORMATION_SCHEMA.TABLES is a bit more declarative -- and it's cross platform (which often doesn't matter at all but meh still nice.)
I think this is probably more readable for a new coder though:
DECLARE @tableName SYSNAME = 'tbfoo'
DECLARE @schemaNAme SYSNAME = 'fooSchema'
IF EXISTS ( SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = @tableName AND TABLE_SCHEMA = @schemaName )
BEGIN
RAISERROR('%s exists in schema: %s', 0, 1, @tableName, @schemaName)
END
ELSE
BEGIN
RAISERROR('%s DOES NOT EXIST in schema: %s', 0, 1, @tableName, @schemaName)
END
Don't worry about the RAISERROR command -- its just a nice way of printing formatted messages.
You can query the INFORMATION_SCHEMA view to get a sense of what's in it.
SELECT TOP 5 * FROM INFORMATION_SCHEMA.TABLES
As you can see -- you can reference schemas and catalogs by name rather than looking up their ID with OBJECT_ID()