20.07.2013 Views

Beginning SQL

Beginning SQL

Beginning SQL

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 4<br />

150<br />

Finally, you do the same thing for the Attendance table, beginning with the NOT NULL constraint:<br />

ALTER TABLE Attendance<br />

ALTER COLUMN LocationId int NOT NULL;<br />

ALTER TABLE Attendance<br />

ALTER COLUMN MemberId int NOT NULL;<br />

Again, for Oracle or My<strong>SQL</strong>, change the code to the following:<br />

ALTER TABLE Attendance<br />

MODIFY LocationId int NOT NULL;<br />

ALTER TABLE Attendance<br />

MODIFY MemberId int NOT NULL;<br />

Then you add the PRIMARY KEY constraint:<br />

ALTER TABLE Attendance<br />

ADD CONSTRAINT attendance_pk PRIMARY KEY (LocationId, MemberId);<br />

Your next objective in improving the database is to prevent columns containing NULL values where<br />

necessary. Good practice is to add the NOT NULL constraint when creating the table. For example, if<br />

the FilmName column contains no value, it makes the whole record rather pointless, as the name is so<br />

essential. On the other hand, having a missing rating is not as much of a problem. Begin by adding a NOT<br />

NULL constraint to the FilmName column. In MS Access or <strong>SQL</strong> Server, use the following code:<br />

ALTER TABLE Films<br />

ALTER COLUMN FilmName varchar(100) NOT NULL;<br />

In Oracle or My<strong>SQL</strong>, type this statement:<br />

ALTER TABLE Films<br />

MODIFY FilmName varchar(100) NOT NULL;<br />

Finally, in IBM DB2, use the following <strong>SQL</strong>:<br />

CREATE TABLE TempFilms<br />

(<br />

FilmId integer NOT NULL,<br />

FilmName varchar(100),<br />

YearReleased integer,<br />

PlotSummary varchar(2000),<br />

AvailableOnDVD char(1),<br />

Rating integer,<br />

CategoryId integer<br />

);<br />

INSERT INTO TempFilms<br />

SELECT * FROM Films;<br />

DROP TABLE Films;<br />

CREATE TABLE Films

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

Saved successfully!

Ooh no, something went wrong!