Monday, October 24, 2016

SQL For creating databases and tables

Create Database Books2

use Books2

Create table book
(
  BookKey int identity(1,1) primary key,
  BookTitle nvarchar(255) not null,
  BookYear int null,
  BookPrice money not null
);

Go

Create table Author
(
   AuthorKey int identity(1,1) primary key,
   AuthorName nvarchar(255) not null
);

Go
Create table AuthorBook
(
  AuthorKey int not null,
  BookKey int not null,
  Constraint pk_AuthorBook primary key (AuthorKey, Bookkey),
  Constraint fk_Author foreign key (AuthorKey) references Author (authorKey),
  Constraint fk_Book foreign key (BookKey) references Book (BookKey)
 );

 Insert into Book(BookTitle, BookYear, BookPrice)
 Values('Charlotte''s Web',1952,7.5),
 ('American Gods',1999,8.50),
 ('The once and Future King',1950, 3.5)

 Insert into Author(AuthorName)
 values('E.B.White'),
 ('Neil Gaiman')

 Insert into AuthorBook(AuthorKey, bookKey)
 Values(1,1),
 (2,2),
 (2,3)

 Select * from Book
 Select * from Author
 Select * from AuthorBook

No comments:

Post a Comment