2. Issuing the CREATE TABLE Statement
To create the Store Location table, you also could have used the CREATE TABLE
statement. SSMS allows you to generate scripts based on existing objects. Thus, you can generate a CREATE TABLE
script for the table you created with the table designer. To generate the CREATE
script, right-click the Store Location table, and go to Script Table as CREATE To New Query Editor Window, as shown in Figure 2.
Figure 2. Ad hoc scripting options available in SSMS
The action New Query Editor Window will produce the following T-SQL script in a new Query Editor window:
USE [VetClinic]
GO
/****** Object: Table [dbo].[Store Location] ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Store Location](
[store_id] [int] NOT NULL,
[store_zip_code] [int] NULL,
CONSTRAINT [PK_Store Location] PRIMARY KEY CLUSTERED
(
[store_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
Normally, when you create a table, you do not need to keep specifying the ANSI_NULLS
or QUOTED_IDENTIFIER
setting. These are in this script only because it was generated by SQL Server. For reference, the SET ANSI_NULL
statement tells SQL how to deal with null values when used in equality
or comparison operators. In a future version of SQL Server, you will
not be able to set this value to OFF
, so plan on keeping it set to ON
, which is the default value. The QUOTED_IDENTIFER
setting tells SQL Server how to handle quotation marks within query
strings.
Let’s examine the CREATE TABLE
statement generated in the script. As with most DDL statements, the
first value you need to specify is the name. In the example, the table
name is Store Location
, and it is created in the dbo
schema.
CREATE TABLE [dbo].[Store Location]
The next two lines in the script supply the column definitions. In this table, we have two integer columns: store_id
and store_zip_code
. In T-SQL, these are defined within the CREATE TABLE
statement as follows:
[store_id] [int] NOT NULL,
[store_zip_code] [int] NULL,
The keyword int
specifies
the integer data type. There are many different types of data types
available to use. An integer allows the user to specify a number between -2,147,483,648
and 2,147,483,647. Different data types require different amounts of
storage space. For example, storing the value of an integer takes 4
bytes. Unless you anticipate there being more than 32,768 stores, you
could save 2 bytes of storage by using a smallint
instead of an int
to define the store_id
column.