Using T-SQL to create tables programmatically
Part two of a four-part series of blogs

SQL doesn’t just select data; you can also use it to create tables and link them together with relationships. This blog shows you how!

  1. Creating Tables in SQL
  2. Creating Databases using SQL (this blog)
  3. Creating a Table Programmatically in SQL
  4. Linking Tables (Foreign Keys and Relationships)

This blog is part of a much longer tutorial on programming in SQL.  Alternatively, have a look at our classroom-based training courses in SQL.

Posted by Andy Brown on 05 October 2012

You need a minimum screen resolution of about 700 pixels width to see our blogs. This is because they contain diagrams and tables which would not be viewable easily on a mobile phone or small laptop. Please use a larger tablet, notebook or desktop computer, or change your screen resolution settings.

Creating Databases using SQL

Tables that you create have to belong in a database, and you can create one of these in SQL.  The command is:

CREATE DATABASE NameOfDatabase

So if you were creating a database to hold books and authors, you might run:

-- create a new database

CREATE DATABASE Literature

As always with SQL, you have to be careful to refresh your server in order to be able to see your new database:

Right-click to refresh databases The Literature database selected
Right-click on Databases ... ... to show your new one.

You can also delete any existing database before creating a new one, to make sure you start with a clean slate:

-- try to delete the database

BEGIN TRY

DROP DATABASE Literature

END TRY

BEGIN CATCH

END CATCH

-- now create a new database

CREATE DATABASE Literature

Now that we've got a database, it's time to create a new table in it!

This blog has 0 threads Add post