How to get table list in database, using MS SQL 2008?

后端 未结 3 517
感动是毒
感动是毒 2021-02-06 23:05

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

3条回答
  •  再見小時候
    2021-02-06 23:09

    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.

提交回复
热议问题