I want to verify if a table exists in a database, and if it doesn\'t exist, to create it. How can I get a list of all the tables in the current database?
I could get the
Answering the question in your title, you can query sys.tables
or sys.objects
where type = 'U'
to check for the existence of a table. You can also use OBJECT_ID('table_name', 'U'). If it returns a non-null value then the table exists:
IF (OBJECT_ID('dbo.My_Table', 'U') IS NULL)
BEGIN
CREATE TABLE dbo.My_Table (...)
END
You can do the same for databases with DB_ID():
IF (DB_ID('My_Database') IS NULL)
BEGIN
CREATE DATABASE My_Database
END
If you want to create the database and then start using it, that needs to be done in separate batches. I don't know the specifics of your case, but there shouldn't be many cases where this isn't possible. In a SQL script you can use GO
statements. In an application it's easy enough to send across a new command after the database is created.
The only place that you might have an issue is if you were trying to do this in a stored procedure and creating databases on the fly like that is usually a bad idea.
If you really need to do this in one batch, you can get around the issue by using EXEC to get around the parsing error of the database not existing:
CREATE DATABASE Test_DB2
IF (OBJECT_ID('Test_DB2.dbo.My_Table', 'U') IS NULL)
BEGIN
EXEC('CREATE TABLE Test_DB2.dbo.My_Table (my_id INT)')
END
EDIT: As others have suggested, the INFORMATION_SCHEMA.TABLES
system view is probably preferable since it is supposedly a standard going forward and possibly between RDBMSs.