I'm reverse engineering a script that creates a payroll database from my textbook. I'm rebuilding it into a library management system instead. To start I've drawn out a diagram of the tables/columns and their relationships here. Now following the script from the textbook I use the authors technique to create all the tables except for the BooksIssued table and InvoiceItems table. This is my code
USE master
GO
/******Check to see if database exists******/
IF DB_ID('SET2133810') IS NOT NULL
DROP DATABASE SET2133810
GO
/******Object: Database SET2133810******/
CREATE DATABASE SET2133810
GO
USE SET2133810
GO
/******Object: table*****/
CREATE TABLE VendorsList(
VendorID int IDENTITY(1,1) NOT NULL,
VendorName varchar(50) NOT NULL,
VendorPhone varchar(50) NULL,
VendorContactLName varchar(50) NULL,
VendorContactFName varchar(50) NULL,
VendorAddress varchar(50) NULL,
VendorCity varchar(50) NOT NULL,
VendorState char(2) NOT NULL,
VendorZipCode varchar(20) NOT NULL,
CONSTRAINT PK_VendorsList PRIMARY KEY CLUSTERED (
VendorID ASC
)
)
GO
/******Object: Table*****/
CREATE TABLE InvoicesList(
InvoiceID int IDENTITY(1,1) NOT NULL,
VendorID int NOT NULL,
InvoiceNumber varchar(50) NOT NULL,
InvoiceDate smalldatetime NOT NULL,
InvoiceTotal money NOT NULL,
PaymentTotal money NOT NULL,
PaymentDate smalldatetime NULL,
CONSTRAINT PK_InvoicesList PRIMARY KEY CLUSTERED(
InvoiceID ASC
)
)
GO
/******Object: Table*****/
CREATE TABLE BookList(
BookID int IDENTITY(1,1) NOT NULL,
BookISBN varchar(50) NOT NULL,
BookTitle varchar(50) NOT NULL,
BookAuthor varchar(50) NOT NULL,
BookPublisher varchar(50) NOT NULL,
BookGenre varchar(50) NULL
CONSTRAINT PK_BookList PRIMARY KEY CLUSTERED(
BookID ASC
)
)
GO
/******Object: Table*****/
CREATE TABLE MembersList(
MemberID int IDENTITY(1,1) NOT NULL,
MemberLName varchar(50) NOT NULL,
MemberFName varchar(50) NOT NULL,
MemberAddress varchar(50) NULL,
MemberCity varchar(50) NOT NULL,
MemberState char(2) NOT NULL,
MemberZipCode varchar(20) NOT NULL,
MemberPhone varchar(50) NOT NULL,
MemberEmail varchar(50) NOT NULL,
CONSTRAINT PK_MembersList PRIMARY KEY CLUSTERED(
MemberID ASC
)
)
GO
I'm confused on how I would create these tables in the same way? Since they both depend on the other tables and the information thats already in them. I've looked around and found Join statements, but none of them were used in a way that would help me with this problem.
Following should be the order to create tables.
BookList
MemeberList
Book Issued
VendorList
InvoiceList
InvoiceItems
Invoice list shoul be created in last as it have references to vendor and invoice items and BookIssues should be created after MemberList and Book List
Related
this is my first hands-on experience with Sql and I'm trying to construct One-To-Many relationship, here is the SQL code:
create table car (
id SERIAL PRIMARY KEY,
make VARCHAR(100) NOT NULL,
model VARCHAR(100) NOT NULL,
price NUMERIC(19, 2) NOT NULL
);
create table person (
id BIGSERIAL NOT NULL PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
gender VARCHAR(7) NOT NULL,
email VARCHAR(100),
date_of_birth DATE NOT NULL,
country_of_birth VARCHAR(50) NOT NULL,
cars_owning INT[] REFERENCES car(id)
);
and I get this error:
Key columns "cars_owning" and "id" are of incompatible types: integer[] and integer.
Here is the model a person can have many cars but each car have only one owner
typically (as a good general rule of thumb) the many refers to the one. not the other way around as you have tried.
So, alter the schema as:
create table car (
id SERIAL PRIMARY KEY,
make VARCHAR(100) NOT NULL,
model VARCHAR(100) NOT NULL,
price NUMERIC(19, 2) NOT NULL,
owner_id BIGINT FOREIGN KEY REFERENCES person(id)
);
create table person (
id BIGSERIAL NOT NULL PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
gender VARCHAR(7) NOT NULL,
email VARCHAR(100),
date_of_birth DATE NOT NULL,
country_of_birth VARCHAR(50) NOT NULL
);
If you need to get the list of cars owned by a person, use this select statement
SELECT person.id, ARRAY_AGG(car.id) owns_car_ids
FROM person
LEFT JOIN car ON person.id = car.owner_id
GROUP BY 1
The ArtistID column in Piece table refers to the ArtistID in the Artist table. Likewise, the LocationID column in Piece refers to LocationID in the GeographicLocation table. However, both foreign key references throw a "not the same data type as referencing column" error. What am I doing wrong?
CREATE TABLE dbo.Artist
(
ArtistID SMALLINT PRIMARY KEY IDENTITY,
LastName VARCHAR(50) NOT NULL,
FirstName VARCHAR(40) NOT NULL,
Nationality VARCHAR(10) NULL,
BirthYear SMALLINT NOT NULL CHECK(BirthYear <= 1980),
DeathYear SMALLINT NULL,
Sex CHAR(1) NOT NULL CHECK(Sex = 'F' OR Sex = 'M')
)
CREATE TABLE dbo.Piece
(
PieceID SMALLINT PRIMARY KEY IDENTITY(1, 5),
ArtistID SMALLINT NOT NULL
FOREIGN KEY REFERENCES Artist(ArtistID),
LocationID SMALLINT NOT NULL
FOREIGN KEY REFERENCES GeographicLocation(LocationID),
CommonName VARCHAR(100) NULL,
YearProduced TINYINT NULL,
Period VARCHAR(50) NULL,
Medium VARCHAR(35) NOT NULL,
Frame VARCHAR(35) NULL,
AppraisedValue MONEY NOT NULL,
AppraiserID SMALLINT NOT NULL
FOREIGN KEY REFERENCES Appraiser(AppraiserID)
)
CREATE TABLE dbo.GeographicLocation
(
LocationID SMALLINT PRIMARY KEY IDENTITY,
Country VARCHAR(25) NOT NULL,
City VARCHAR(50) NOT NULL
)
I think you missed a table here, which is AppraiserID column in Piece table refers to the AppraiserID in the Appraisertable
So, when I execute your SQL I am getting below error:
Foreign key 'FK__Piece__Appraiser__322C6448' references invalid table 'Appraiser'.
First Create a table called Appraiser, then create Foreign key references for those column.
Below SQL I am able to create all tables and Foreign key references:
CREATE TABLE dbo.Artist
(ArtistID SMALLINT PRIMARY KEY IDENTITY,
LastName VARCHAR(50) NOT NULL,
FirstName VARCHAR(40) NOT NULL,
Nationality VARCHAR(10) NULL,
BirthYear SMALLINT NOT NULL CHECK(BirthYear <= 1980),
DeathYear SMALLINT NULL,
Gender CHAR(1) NOT NULL CHECK(Gender = 'F' OR Gender = 'M'))
CREATE TABLE dbo.GeographicLocation
(LocationID SMALLINT PRIMARY KEY IDENTITY,
Country VARCHAR(25) NOT NULL,
City VARCHAR(50) NOT NULL)
CREATE TABLE dbo.Appraiser
(AppraiserID SMALLINT PRIMARY KEY IDENTITY(1, 5),
AppraisedValue MONEY NOT NULL,
AppraisedName VARCHAR(100) NULL)
CREATE TABLE dbo.Piece
(PieceID SMALLINT PRIMARY KEY IDENTITY(1, 5),
ArtistID SMALLINT NOT NULL,
LocationID SMALLINT NOT NULL,
CommonName VARCHAR(100) NULL,
YearProduced TINYINT NULL,
Period VARCHAR(50) NULL,
Medium VARCHAR(35) NOT NULL,
Frame VARCHAR(35) NULL,
AppraisedValue MONEY NOT NULL,
AppraiserID SMALLINT NOT NULL)
ALTER TABLE dbo.Piece WITH CHECK ADD CONSTRAINT FK_Piece_ArtistID FOREIGN KEY(ArtistID)
REFERENCES dbo.Artist (ArtistID)
GO
ALTER TABLE dbo.Piece CHECK CONSTRAINT FK_Piece_ArtistID
GO
ALTER TABLE dbo.Piece WITH CHECK ADD CONSTRAINT FK_Piece_AppraiserID FOREIGN KEY(AppraiserID)
REFERENCES dbo.Appraiser (AppraiserID)
GO
ALTER TABLE dbo.Piece CHECK CONSTRAINT FK_Piece_AppraiserID
GO
ALTER TABLE dbo.Piece WITH CHECK ADD CONSTRAINT FK_Piece_LocationID FOREIGN KEY(LocationID)
REFERENCES dbo.GeographicLocation (LocationID)
GO
ALTER TABLE dbo.Piece CHECK CONSTRAINT FK_Piece_LocationID
GO
I have written the following stored procedure to return data based on a lat/long and category id being passed.
I need to return a list of traders whose coverage area falls within the passed lat long (and that they cover the category being passed). So I am looking to draw a circle around the traders lat/long position, x number of meters using the radius they will operate from (this is stored in the Traders.OperatingRadius column). If the passed lat long coord is within this, then they should be included in the return list.
CREATE PROCEDURE FindTradersWithinRadiusLatLong
#LAT decimal(9,6),
#LONG decimal(9,6),
#CATEGORY int
AS
BEGIN
SET NOCOUNT ON;
DECLARE #GEO1 GEOGRAPHY;
SET #GEO1 = geography::Point(#LAT, #LONG, 4326)
SELECT
x.Id, x.Name,
x.Latitude, x.Longitude,
x.Distance, x.IsArchived
FROM
(SELECT
Traders.Id, Traders.Name,
Latitude, Longitude,
CategoryId = TraderCategories.Id,
OperatingRadius,
Traders.IsArchived,
Distance = (#geo1.STDistance(geography::Point(ISNULL(Latitude, 0), ISNULL(Longitude, 0), 4326)))
FROM
((Addresses
INNER JOIN
Traders ON Addresses.TraderId = Traders.Id)
INNER JOIN
TraderCategories ON Traders.Id = TraderCategories.TraderId)) AS x
WHERE
x.Distance <= x.OperatingRadius
AND x.CategoryId = #CATEGORY
AND (x.IsArchived = 0 OR x.IsArchived = NULL);
END
GO
TraderCategories is a linking table as follows;
Table TraderCategories
int FK TraderId
int FK CategoryId
Now I have added an address with;
latitiude - 43.590000, Longitude - -111.120000
There is also a TraderCategory Relationship for category with Id 1
I have then tried calling the stored procedure with the above and no matches are being returned.
The table definitions are as follows:
CREATE TABLE [Bemfeito].[Addresses]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[Address1] [nvarchar](max) NULL,
[Address2] [nvarchar](max) NULL,
[Address3] [nvarchar](max) NULL,
[TraderId] [int] NULL,
[Latitude] [decimal](9, 6) NOT NULL,
[Longitude] [decimal](9, 6) NOT NULL,
[OperatingRadius] [real] NOT NULL DEFAULT (CONVERT([real],(0)))
CONSTRAINT [PK_Addresses]
PRIMARY KEY CLUSTERED ([Id] ASC)
)
GO
ALTER TABLE [Bemfeito].[Addresses] WITH CHECK
ADD CONSTRAINT [FK_Addresses_Traders_TraderId]
FOREIGN KEY([TraderId]) REFERENCES [Bemfeito].[Traders] ([Id])
GO
ALTER TABLE [Bemfeito].[Addresses] CHECK CONSTRAINT [FK_Addresses_Traders_TraderId]
GO
CREATE TABLE [Bemfeito].[Traders]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[Email] [nvarchar](max) NULL
[Name] [nvarchar](max) NULL
CONSTRAINT [PK_Traders]
PRIMARY KEY CLUSTERED ([Id] ASC)
)
GO
CREATE TABLE [Bemfeito].[TraderCategories]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[CategoryId] [int] NULL,
[TraderId] [int] NULL,
CONSTRAINT [PK_TraderCategories]
PRIMARY KEY CLUSTERED ([Id] ASC)
)
GO
ALTER TABLE [Bemfeito].[TraderCategories] WITH CHECK
ADD CONSTRAINT [FK_TraderCategories_Categories_CategoryId]
FOREIGN KEY([CategoryId]) REFERENCES [Bemfeito].[Categories] ([Id])
GO
ALTER TABLE [Bemfeito].[TraderCategories] CHECK CONSTRAINT [FK_TraderCategories_Categories_CategoryId]
GO
ALTER TABLE [Bemfeito].[TraderCategories] WITH CHECK
ADD CONSTRAINT [FK_TraderCategories_Traders_TraderId]
FOREIGN KEY([TraderId]) REFERENCES [Bemfeito].[Traders] ([Id])
GO
ALTER TABLE [Bemfeito].[TraderCategories] CHECK CONSTRAINT [FK_TraderCategories_Traders_TraderId]
GO
and finally for completion the category
CREATE TABLE [Bemfeito].[Categories]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](max) NULL,
[Value] [int] NOT NULL,
CONSTRAINT [PK_Categories]
PRIMARY KEY CLUSTERED ([Id] ASC)
)
Can anyone tell me where I am going wrong here please?
If you look at this microsoft reference here you should notice that the argument passed to STDistance is a geometry datatype while you are passing a Point datatype.
the line currently written like this
,Distance = (#geo1.STDistance(geography::Point(ISNULL(Latitude, 0), ISNULL(Longitude, 0), 4326))
should be written as follows.
,Distance = (#geo1.STDistance(geography::STGeomFromText('Point('+ISNULL(Longitude, 0)+' '+ISNULL(Latitude, 0)')',4326))
This is my task list:
Design a star or snowflake schema for a data warehouse that will help answer various business questions regarding sales.
Create a database in SQL Server (this is the data warehouse server) based on the star/snowflake schema you designed.
Load data from the source system i.e. the OLTP database shown earlier to the star/snowflake schema database.
The data from most of the tables in the OLTP database have been prepared in a form of SQL statements. Unfortunately, due to company's policy, you are not allowed to load data from the Products and Customer table 'directly'.
The Customer data has been prepared in CSV format
The Product data can only be retrieved from cloud database in JSON format http://bi.edisonsiow.com/ay1516s2/ca1/getProducts.php
You are required to find the most efficient way, which might include coding, to load data from the sources to your SQL Server.
So far i have done this :
CREATE TABLE Customers (
customerNumber Int NOT NULL,
customerName Varchar(50) NOT NULL,
contactLastName Varchar(50) NOT NULL,
contactFirstName Varchar(50) NOT NULL,
phone Varchar (50) NOT NULL,
addressLine1 Varchar (50) NOT NULL,
addressLine2 Varchar (50) NOT NULL,
city Varchar (50) NOT NULL,
state Varchar (50) NULL,
postalCode Varchar (15) NOT NULL,
country Varchar(50) NOT NULL,
salesRepEmployeeNumber Int NOT NULL,
creditLimit Double NOT NULL,
PRIMARY KEY (customerNumber));
CREATE TABLE Offices (
officeCode Varchar(10) NOT NULL,
city Varchar(50) NOT NULL,
phone Varchar(50) NOT NULL,
addressLine1 Varchar(50) NOT NULL,
addressLine2 Varchar(50) NOT NULL,
state Varchar(50) NULL,
country Varchar(50) NOT NULL,
postalCode Varchar(15) NOT NULL,
territory Varchar(10) NOT NULL,
PRIMARY KEY (officeCode));
CREATE TABLE payments (
customerNumber Int NOT NULL,
checkNumber Varchar(50) NOT NULL,
paymentDate Datetime NOT NULL,
amount DOUBLE NOT NULL,
PRIMARY KEY (customerNumber, checkNumber));
CREATE TABLE OrderDetails (
orderNumber Int NOT NULL,
productCode Varchar(15) NOT NULL,
quantityOrdered Int NOT NULL,
priceEach DOUBLE NOT NULL,
orderLineNumber SMALLINT NOT NULL,
PRIMARY KEY (orderNumber, productCode));
CREATE TABLE ProductLines (
productLine Varchar (50) NOT NULL,
textDescription TEXT NOT NULL,
htmlDescription TEXT NOT NULL,
image BLOB NOT NULL,
PRIMARY KEY (productLine));
CREATE TABLE Orders (
orderNumber Int NOT NULL,
orderDate DateTime NOT NULL,
requiredDate DateTime NOT NULL,
shippedDate DateTime NOT NULL,
status Varchar(15) Not null,
comments TEXT NOT NULL,
customerNumber INT NOT NULL,
Primary key(orderNumber));
ALTER TABLE Orders ADD FOREIGN KEY(customerNumber) REFERENCES Customer(customerNumber);
CREATE TABLE Employees (
employeeNumber Int Not null,
lastName Varchar(50) Not null,
firstName Varchar(50) Not null,
extension Varchar(10) NOt null,
email Varchar(100) Not null,
officeCode Varchar(10) Not Null,
reportsTo Int Not null,
jobTitle Varchar(50) Not null,
Primary key(employeeNumber));
CREATE TABLE Products (
productCode Varchar(15) Not Null,
productName Varchar(70) Not Null,
productLine Varchar(50) Not null,
productScale Varchar(10) Not null,
productVendor Varchar(50) Not null,
productDescription TEXT Not null,
quantityinStock Int Not null,
Buy Price Double Not null,
MSRP Double Not null,
Primary key (productCode))
9:28PM
CREATE TABLE payments (
customerNumber Int NOT NULL,
checkNumber Varchar(50) NOT NULL,
paymentDate Datetime NOT NULL,
amount Float NOT NULL,
PRIMARY KEY (customerNumber, checkNumber));
CREATE TABLE Customers (
customerNumber Int NOT NULL,
customerName Varchar(50) NOT NULL,
contactLastName Varchar(50) NOT NULL,
contactFirstName Varchar(50) NOT NULL,
phone Varchar (50) NOT NULL,
addressLine1 Varchar (50) NOT NULL,
addressLine2 Varchar (50) NOT NULL,
city Varchar (50) NOT NULL,
state Varchar (50) NULL,
postalCode Varchar (15) NOT NULL,
country Varchar(50) NOT NULL,
salesRepEmployeeNumber Int NOT NULL,
creditLimit Float NOT NULL,
PRIMARY KEY (customerNumber));
ALTER TABLE Payments ADD FOREIGN KEY(customerNumber) REFERENCES Customers(customerNumber); -- here
CREATE TABLE Offices (
officeCode Varchar(10) NOT NULL,
city Varchar(50) NOT NULL,
phone Varchar(50) NOT NULL,
addressLine1 Varchar(50) NOT NULL,
addressLine2 Varchar(50) NOT NULL,
state Varchar(50) NULL,
country Varchar(50) NOT NULL,
postalCode Varchar(15) NOT NULL,
territory Varchar(10) NOT NULL,
PRIMARY KEY (officeCode));
CREATE TABLE OrderDetails (
orderNumber Int NOT NULL,
productCode Varchar(15) NOT NULL,
quantityOrdered Int NOT NULL,
priceEach Float NOT NULL,
orderLineNumber SMALLINT NOT NULL,
PRIMARY KEY (orderNumber, productCode));
CREATE TABLE ProductLines (
productLine Varchar (50) NOT NULL,
textDescription TEXT NOT NULL,
htmlDescription TEXT NOT NULL,
image Float NOT NULL,
PRIMARY KEY (productLine));
CREATE TABLE Orders (
orderNumber Int NOT NULL,
orderDate DateTime NOT NULL,
requiredDate DateTime NOT NULL,
shippedDate DateTime NOT NULL,
status Varchar(15) Not null,
comments TEXT NOT NULL,
customerNumber INT NOT NULL,
Primary key(orderNumber));
ALTER TABLE OrderDetails ADD FOREIGN KEY(orderNumber) REFERENCES Orders(orderNumber); -- here
CREATE TABLE Employees (
employeeNumber Int Not null,
lastName Varchar(50) Not null,
firstName Varchar(50) Not null,
extension Varchar(10) NOt null,
email Varchar(100) Not null,
officeCode Varchar(10) Not Null,
reportsTo Int Not null,
jobTitle Varchar(50) Not null,
Primary key(employeeNumber));
CREATE TABLE Products (
productCode Varchar(15) Not Null,
productName Varchar(70) Not Null,
productLine Varchar(50) Not null,
productScale Varchar(10) Not null,
productVendor Varchar(50) Not null,
productDescription TEXT Not null,
quantityinStock Int Not null,
BuyPrice Float Not null,
MSRP Float Not null,
Primary key (productCode))
ALTER TABLE OrderDetails ADD FOREIGN KEY(productCode) REFERENCES Products(productCode);
I dont know how to load from source system?
In SQL Server Management Studio, exp[and the server-name, and under databases, find your database.
Right-click it, select Tasks, and then Import Data.
Use the import/export wizard to assist you in importing data from your source data.
I am new to SQL and I am trying to create a table with a constraint but I have not used the constrant before and I am not actually certain what this constraint does uc_ID on PId, LastName?
I want to create a constraint that will only allow alpha numeric values in a column?
Code:
CREATE TABLE Persons
(
PId int identity(1,1) NOT NULL,
LastName varchar(25) NOT NULL,
FirstName varchar(25) NOT NULL,
Address1 varchar(25) NOT NULL,
City varchar(25) NOT NULL
CONSTRAINT uc_ID UNIQUE (PId,LastName)
)
CREATE TABLE E
(
PId int identity(1,1) NOT NULL,
LastName varchar (25) NOT NULL,
FirstName varchar (25) NOT NULL,
Address1 varchar (25) NOT NULL,
City varchar (25) NOT NULL
CONSTRAINT OnlyAlphanumeric CHECK ([FirstName] NOT LIKE '%[^A-Z0-9]%')
)
Another Example (is not):
CREATE TABLE EEE
(
PId int identity(1,1) NOT NULL,
FirstName varchar (50) NOT NULL,
CONSTRAINT CHECK ([FirstName] LIKE '%[A-Za-z]%')
)
Means that the combination of Pid + LastName must be unique.
Since Pid is an identity, in normal circumstances it cannot be duplicated, so that constraint seems somehow redudant.
Try:
ALTER TABLE TableName ADD CONSTRAINT Only_Characters_And_Numbers CHECK ColumnName NOT LIKE '%[^A-Z0-9 ]%'
If you want a constraint that allows only alphanumeric characters in a column you can use this (for example for FirstName:
ALTER TABLE [Persons] ADD CONSTRAINT OnlyAlphanumeric CHECK ([FirstName] NOT LIKE '%[^A-Z0-9 ]%')
Disclaimer: taken from here (and tested).
If you want the constraint to be added when the table is created:
CREATE TABLE Persons
(
PId int identity(1,1) NOT NULL,
LastName varchar(25) NOT NULL,
FirstName varchar(25) NOT NULL,
Address1 varchar(25) NOT NULL,
City varchar(25) NOT NULL
CONSTRAINT OnlyAlphanumeric CHECK ([FirstName] NOT LIKE '%[^A-Z0-9 ]%')
)
Note that constraint names are unique per database.
Alternatively, you can create an AFTER INSERT and AFTER UPDATE trigger to make this validation, but a constraint works just fine in this case.