Data definition language statements

Let's start with data definition language statements. The following code shows how to create a simple table. This table represents customers' orders. For this demonstration of the DDL and DML statements, only a couple of columns are created in the table. The OrderId column uniquely identifies each row in this table, and is a primary key for the table, as the PRIMARY KEY constraint specifies. Finally, the code checks first if a table with the name SimpleOrders in the dbo schema already exists, and drops it if true:

IF OBJECT_ID(N'dbo.SimpleOrders', N'U') IS NOT NULL 
   DROP TABLE dbo.SimpleOrders; 
CREATE TABLE dbo.SimpleOrders 
( 
  OrderId   INT         NOT NULL, 
  OrderDate DATE        NOT NULL, 
  Customer  NVARCHAR(5) NOT NULL, 
  CONSTRAINT PK_SimpleOrders PRIMARY KEY (OrderId) 
); 

For further examples, another table is needed. The following code creates the dbo.SimpleOrderDetails table, created in a very similar way to the previous table, by checking for its existence and dropping it if it exists first. The OrderId and ProductId columns form a composite primary key. In addition, a CHECK constraint on the Quantity column prevents inserts or updates of this column to value zero:

IF OBJECT_ID(N'dbo.SimpleOrderDetails', N'U') IS NOT NULL 
   DROP TABLE dbo.SimpleOrderDetails; 
CREATE TABLE dbo.SimpleOrderDetails 
( 
  OrderId   INT NOT NULL, 
  ProductId INT NOT NULL, 
  Quantity  INT NOT NULL 
   CHECK(Quantity <> 0), 
  CONSTRAINT PK_SimpleOrderDetails 
   PRIMARY KEY (OrderId, ProductId) 
); 

The previous two examples show how to add constraints when you create a table. It is also always possible to add constraints later, by using the ALTER TABLE statement. The tables created in the previous two examples are associated through a foreign key. The primary key of the dbo.SimpleOrders table is associating the order details in the dbo.SimpleOrders table with their correspondent order. The code in the following example defines this association:

ALTER TABLE dbo.SimpleOrderDetails ADD CONSTRAINT FK_Details_Orders 
FOREIGN KEY (OrderId) REFERENCES dbo.SimpleOrders(OrderId); 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.131.255