Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 database list with a SELECT like this:

SELECT * FROM sys.databases 

What's left is to create the table if it doesn't exist.

I also tried to create the tables at the same time with the database like this:

if not exists(select * from sys.databases where name = 'db') begin      create database [db]     use [db];     create table [test] (          Time datetime,          Message varchar(1024) )     end 

But it gives me error on the 'use' line, saying that 'db' doesn't exist. This time, I will try to do this in 2 different commands.

like image 684
Tibi Avatar asked Jul 06 '11 14:07

Tibi


People also ask

How do I get a list of table names in a database?

In MySQL, there are two ways to find the names of all tables, either by using the "show" keyword or by query INFORMATION_SCHEMA. In the case of SQL Server or MSSQL, You can either use sys. tables or INFORMATION_SCHEMA to get all table names for a database.

How can I see all tables in SQL database?

The easiest way to find all tables in SQL is to query the INFORMATION_SCHEMA views. You do this by specifying the information schema, then the “tables” view. Here's an example. SELECT table_name, table_schema, table_type FROM information_schema.


2 Answers

This should give you a list of all the tables in your database

SELECT Distinct TABLE_NAME FROM information_schema.TABLES 

So you can use it similar to your database check.

If NOT EXISTS(SELECT Distinct TABLE_NAME FROM information_schema.TABLES Where TABLE_NAME = 'Your_Table') BEGIN     --CREATE TABLE Your_Table END GO 
like image 81
Brandon Boone Avatar answered Sep 24 '22 17:09

Brandon Boone


This query will get you all the tables in the database

USE [DatabaseName];  SELECT * FROM information_schema.tables; 
like image 37
John Hartsock Avatar answered Sep 21 '22 17:09

John Hartsock