17.06.2013 Views

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 6: Constraints<br />

Defining a DEFAULT Constraint in Your<br />

CREATE TABLE Statement<br />

174<br />

Under the heading of “One more thing,” it’s worth noting that there is an exception<br />

to the rule about an UPDATE command not using a default. The exception happens if<br />

you explicitly say that you want a default to be used. You do this by using the keyword<br />

DEFAULT as the value you want the column updated to.<br />

At the risk of sounding repetitious, this works pretty much like all the other column constraints we’ve<br />

dealt with thus far. You just add it to the end of the column definition.<br />

To work an example, start by dropping the existing Shippers table that we created earlier in the chapter.<br />

This time, we’ll create a simpler version of that table, including a default:<br />

CREATE TABLE Shippers<br />

(<br />

ShipperID int IDENTITY NOT NULL<br />

PRIMARY KEY,<br />

ShipperName varchar(30) NOT NULL,<br />

DateInSystem smalldatetime NOT NULL<br />

DEFAULT GETDATE ()<br />

);<br />

After you run your CREATE script, you can again make use of sp_helpconstraint to show you what<br />

you have done. You can then test how your default works by inserting a new record:<br />

INSERT INTO Shippers<br />

(ShipperName)<br />

VALUES<br />

(‘United Parcel Service’);<br />

Then run a SELECT statement on your Shippers table:<br />

SELECT * FROM Shippers;<br />

The default value has been generated for the DateInSystem column since we didn’t supply a value<br />

ourselves:<br />

ShipperID ShipperName DateInSystem<br />

-------------------------------------- ---------------------------<br />

1 United Parcel Service <strong>2008</strong>-07-31 23:26:00<br />

(1 row(s) affected)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!