Using T-SQL to create tables programmatically
Part one 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 (this blog)
  2. Creating Databases using SQL
  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 Tables in SQL

This blog shows how you can use SQL to create tables.  All of the SQL that you'll need will be shown as we go along.  Just before we begin, though, let's look at two alternatives to writing SQL code.

Alternatives to Creating Tables Programmatically

It probably goes without saying, but you don't need to write SQL script to create tables:

Authors table design view

You can design tables in SQL Server Management Studio (SSMS), specifiying for each column a name and a data type.


Scripting Table Creation

If you already have a table, you can use this to generate SQL script:

Menu option to script a table

You can right-click on any table in SSMS and choose to create a new table from it.

This will generate script, which you can then edit as you see fit:

Script generated by authors table

A small part of the script generated by the above menu option.

However, this blog is going to concentrate on writing script from scratch.

If you're wondering why this might be a useful thing to do, SQL works with sets of rows at a time, and it's frequently useful to create ad hoc temporary tables to hold these.

To start with, let's look at how you might first create a database to hold your tables.

This blog has 0 threads Add post