SQL 2008 create table method and KEY - sql

I've got a script that generates a table - only my version of SQL 2008 throws up an error - has the syntax changed? Or how do I fix it manually?
CREATE TABLE ScoHistory (
CourseID varchar (255) NOT NULL ,
SessionID int NOT NULL ,
ScoID varchar (255) NOT NULL ,
StudentID varchar (255) NOT NULL ,
DateRecorded datetime NULL ,
score_raw varchar (12) NULL,
KEY student_course_sess_scohist_idx (StudentID, CourseID, SessionID, ScoID) -- this is the bit it doesn't like! It says incorrect syntax near KEY...
);
Many thanks in advance,
Spud

You can define a named primary key table constraint like this:
CREATE TABLE ScoHistory (
CourseID varchar (255) NOT NULL,
SessionID int NOT NULL,
ScoID varchar (255) NOT NULL,
StudentID varchar (255) NOT NULL,
DateRecorded datetime NULL,
score_raw varchar (12) NULL,
CONSTRAINT student_course_sess_scohist_idx PRIMARY KEY (StudentID, CourseID, SessionID, ScoID)
);

It would work like this, if this is the intended behaviour:
CREATE TABLE ScoHistory (
CourseID varchar (255) NOT NULL ,
SessionID int NOT NULL ,
ScoID varchar (255) NOT NULL ,
StudentID varchar (255) NOT NULL ,
DateRecorded datetime NULL ,
score_raw varchar (12) NULL,
PRIMARY KEY (StudentID, CourseID, SessionID, ScoID)
);
It you would only like to create a non-unique index on the table, create the index using the CREATE INDEX statement.

CREATE TABLE ScoHistory
(
CourseID varchar(255) NOT NULL
,SessionID int NOT NULL
,ScoID varchar(255) NOT NULL
,StudentID varchar(255) NOT NULL
,DateRecorded datetime NULL
,score_raw varchar(12) NULL,
) ;
ALTER TABLE dbo.ScoHistory ADD
CONSTRAINT PK_ScoHistory PRIMARY KEY (StudentID, CourseID, SessionID, ScoID);

Related

SQL error while creating a new table, what am I missing

create table paydetails (
emp_id integer (20),
dept_id integer (20),
basic integer(20),
deductions integer(20),
additions integer (20),
joining_date date(20,20,20)
);
This should work in almost any database:
create table paydetails (
emp_id int,
dept_id int,
basic int,
deductions int,
additions int,
joining_date date
);
Most databases do not have a parameter for int (although some interpret that as a length).
As far as I know, none have three parameters for date.
This will work for you. Do yourself the favor of adding in the auto increment id as your unique/primary key.
CREATE TABLE `db_name`.`paydetails` (
`id` INT(20) NOT NULL AUTO_INCREMENT ,
`emp_id` INT(20) NOT NULL ,
`dept_id` INT(20) NOT NULL ,
`basic` INT(20) NOT NULL ,
`deductions` INT(20) NOT NULL ,
`additions` INT(20) NOT NULL ,
`joining_date` DATE NOT NULL ,
PRIMARY KEY (`id`)) ENGINE = MyISAM;

How to make (patient id) forgein key in table of bill?

I try to create three tables by using website suport compiler any code but I have a problem in the table of the bill.
When I run it I get to error show me it is near in foreign key
These are codes of three tables
CREATE TABLE patient (
Patient Id (5) Primary key,
Name Varchar (20) Not null ,
Age Int Not null ,
Weight Int Not null ,
Gender Varchar (10) Not null,
Address Varchar (50) Not null ,
Disease Varchar (20) Not null
);
CREATE TABLE doctors (
DoctorId Varchar (5) Primary key,
Doctorname Varchar (15) Not null,
Dept Varchar (15) Not null
);
CREATE TABLE bill (
Bill_no Varchar (50) Primary key,
Patient_Id Varchar (5) Foreign key,,
doctor_charge Int Not null,
patient_type Varchar (10) null,
no_of_days Int null,
lab_charge Int null,
bill Int Not null
);
Patient Table
CREATE TABLE patient
(
patient_id VARCHAR (5) PRIMARY KEY,
name VARCHAR (20) NOT NULL,
age INT NOT NULL,
weight INT NOT NULL,
gender VARCHAR (10) NOT NULL,
address VARCHAR (50) NOT NULL,
disease VARCHAR (20) NOT NULL
);
Errors
No data type has been assigned in Patient id column (Patient Id (5)
Primary key)
Patient id column name contains spaces. You need to
enclose the column name in double quotes or replace space with something else
(ex: _). It's not recommended to use spaces.
A column name with space
CREATE TABLE tablename ("column name" datatype);
Doctors Table
CREATE TABLE doctors
(
doctorid VARCHAR (5) PRIMARY KEY,
doctorname VARCHAR (15) NOT NULL,
dept VARCHAR (15) NOT NULL
);
Bill Table
CREATE TABLE bill
(
bill_no VARCHAR (50) PRIMARY KEY,
patient_id VARCHAR (5),
doctor_charge INT NOT NULL,
patient_type VARCHAR (10) NULL,
no_of_days INT NULL,
lab_charge INT NULL,
bill INT NOT NULL,
FOREIGN KEY (patient_id) REFERENCES patient(patient_id)
);
Errors
The way you have assigned foreign key is wrong. Please refer this and this article for more information. (Patient_Id Varchar (5) Foreign key,,)
There are two commans in the Patient_Id column (Patient_Id Varchar (5) Foreign key,,)
You have to provide reference of the table for which you want to use the reference key.
For example, you have table Persons which has Primary key PersonID, in that case if you want to use that as foreign key in another table, lets say Orders.
In Oracle
CREATE TABLE Orders (
OrderID numeric(10) not null,
OrderNumber numeric(10) not null,
PersonID numeric(10) not null,
CONSTRAINT fk_person_id
FOREIGN KEY (PersonID )
REFERENCES Persons(PersonID )
Your Case :
CREATE TABLE bill
( Bill_no Varchar (50) Primary key,
Patient_Id Varchar (5),
doctor_charge Int Not null,
patient_type Varchar (10) null,
no_of_days Int null,
lab_charge Int null,
bill Int Not null,
CONSTRAINT fk_patient_id
FOREIGN KEY (Patient_Id)
REFERENCES patient(Patient_Id)
);
Remove the 'Foreign Key' from the table creation script.
Add this to your SQL script:
ALTER TABLE [Bill] WITH CHECK ADD CONSTRAINT [FK_Bill_Patient] FOREIGN KEY([Patient_Id])
REFERENCES [Patient] ([Patient_Id])
GO
ALTER TABLE [Bill] CHECK CONSTRAINT [FK_Bill_Patient]
GO
The words FOREIGN KEY are only needed for introducing the name of the FK constraint. Since your other constraints are not named, you might as well skip that part and go straight to REFERENCES.
If you specify a foreign key constraint as part of the column definition, you can omit the datatype to allow it to inherit from its parent at the time of creation, which I think is good practice as the types will automatically match.
We use VARCHAR2 in Oracle, not VARCHAR.
You don't need to specify NULL for columns that are allowed to be null.
I am not sure a 5-character string is a good datatype for a unique ID. How will you generate the values? Normally an auto-incrementing sequence number simplifies this.
create table doctors
( doctorid varchar2(5) primary key
, doctorname varchar2(15) not null
, dept varchar2(15) not null );
create table patients
( patient_id varchar2(5) primary key
, name varchar2(20) not null
, age integer not null
, weight integer not null
, gender varchar2(10) not null
, address varchar2(50) not null
, disease varchar2(20) not null );
create table bills
( bill_no varchar2(50) primary key
, patient_id references patients -- Allow datatype to inherit from parent
, patient_type varchar2(10)
, no_of_days integer
, lab_charge integer
, bill integer not null );

AUTO_INCREMENT doesn't work in SQL server 2012?

CREATE TABLE detectives(
id INTEGER NOT NULL AUTO_INCREMENT,
first_name VARCHAR(50),
last_name VARCHAR(50) NOT NULL,
phone_number VARCHAR(10) NOT NULL,
certification_date DATE NOT NULL,
CONSTRAINT detectives_pk PRIMARY KEY (id
);
It says: Incorrect syntax near 'AUTO_INCREMENT'.
Any help with this?
Missing closing ) and using incorrect syntax for an IDENTITY field.
CREATE TABLE detectives(
id INT IDENTITY,
first_name VARCHAR(50),
last_name VARCHAR(50) NOT NULL,
phone_number VARCHAR(10) NOT NULL,
certification_date DATE NOT NULL,
CONSTRAINT detectives_pk PRIMARY KEY (id)
)
Change
id INTEGER NOT NULL AUTO_INCREMENT,
To
ID INT NOT NULL IDENTITY(1,1),
you've to make the column identity if you want auto increment. your code will be
CREATE TABLE detectives(
id INT NOT NULL IDENTITY (1, 1),
first_name VARCHAR(50),
last_name VARCHAR(50) NOT NULL,
phone_number VARCHAR(10) NOT NULL,
certification_date DATE NOT NULL,
CONSTRAINT detectives_pk PRIMARY KEY (id)
);

st_distance using parents geometry

I have two parent tables as below
CREATE TABLE GISD.CUSTOMERS
(CUSTOMER_ID INTEGER NOT NULL,
FIRST_NAME VARCHAR (15) NOT NULL,
SURNAME VARCHAR (20) NOT NULL,
DATE_OF_BIRTH DATE NOT NULL,
HOUSE_NUMBER VARCHAR (5) NOT NULL
POST_CODE VARCHAR(8) NOT NULL,
STREET VARCHAR (25) NOT NULL,
TOWN VARCHAR (25) NOT NULL
);
SELECT ADDGEOMETRYCOLUMN('gisd','customers', 'customers_geom', '27700','POINT',2);
and
CREATE TABLE GISD.CINEMAS
(CINEMA_ID INTEGER NOT NULL,
CINEMA_NAME VARCHAR(25) NOT NULL,
ADDRESS_NUMBER INTEGER NOT NULL,
POST_CODE VARCHAR(8) NOT NULL,
STREET VARCHAR (25) NOT NULL,
TOWN VARCHAR (25) NOT NULL,
OPENING_TIME TIME NOT NULL,
CLOSING_TIME TIME NOT NULL
);
SELECT ADDGEOMETRYCOLUMN('gisd','cinemas', 'cinemas_geom', '27700','POLYGON',2);
SELECT ADDGEOMETRYCOLUMN('gisd','cinemas', 'centroid', '27700','POINT',2);
I have a child which uses foreign keys from both these tables as such:
CREATE TABLE GISD.BOOKING
(BOOKING_ID INTEGER NOT NULL,
CUSTOMER_ID INTEGER NOT NULL,
CINEMA_ID INTEGER NOT NULL,
TIME TIME NOT NULL,
DATE DATE NOT NULL,
FILM VARCHAR(50) NOT NULL,
BOOKING_METHOD VARCHAR (15) NOT NULL,
BOOKING_FEE NUMERIC NOT NULL -- Numeric is suggested by postgresql.org for currency
TICKET_PRICE NUMERIC NOT NULL
);
is there a way that will allow me to take a unique booking id and reference back to the customer geometry and cinema geometry to calculate an ST_Distance? I assume some sort of nested query could do this but am having no luck?
cheers
UPDATE (from comment)
I have tried the following code:
SELECT (ST_DISTANCE(
(SELECT centroid
FROM GISD.CINEMAS
INNER JOIN GISD.BOOKING ON CINEMAS.CINEMA_ID=BOOKING.CINEMA_ID
),(
SELECT customers_geom
FROM GISD.CUSTOMERS
INNER JOIN GISD.BOOKING ON CUSTOMERS.CUSTOMER_ID=BOOKING.CUSTOMER_ID
)
))
but get an error saying 'more than one row returned by a subquery used as an expression' Any ideas how to get round this? I ideally want it to return the distance for each booking ID
Corrected schema with primary/foreign keys and LOWERCASED names.
DROP SCHEMA tmp CASCADE;
CREATE SCHEMA tmp;
SET search_path=tmp;
CREATE TABLE tmp.customers
( customer_id INTEGER NOT NULL PRIMARY KEY
, first_name VARCHAR (15) NOT NULL
, surname VARCHAR (20) NOT NULL
, date_of_birth DATE NOT NULL
, house_number VARCHAR (5) NOT NULL
, post_code VARCHAR(8) NOT NULL
, street VARCHAR (25) NOT NULL
, town VARCHAR (25) NOT NULL
);
SELECT addgeometrycolumn('tmp','customers', 'customers_geom', '27700','POINT',2);
-- and
CREATE TABLE tmp.cinemas
( cinema_id INTEGER NOT NULL PRIMARY KEY
, cinema_name VARCHAR(25) NOT NULL
, address_number INTEGER NOT NULL
, post_code VARCHAR(8) NOT NULL
, street VARCHAR (25) NOT NULL
, town VARCHAR (25) NOT NULL
, opening_time TIME NOT NULL
, closing_time TIME NOT NULL
);
SELECT addgeometrycolumn('tmp','cinemas', 'cinemas_geom', '27700','POLYGON',2);
SELECT addgeometrycolumn('tmp','cinemas', 'centroid', '27700','POINT',2);
-- I have a junction table between these tables as such:
CREATE TABLE tmp.BOOKING
( booking_id INTEGER NOT NULL PRIMARY KEY
, customer_id INTEGER NOT NULL REFERENCES tmp.customers (customet_id)
, cinema_id INTEGER NOT NULL REFERENCES tmp.cinemas (cinema_id)
, zdatetime timestamp NOT NULL
, film VARCHAR(50) NOT NULL
, booking_method VARCHAR (15) NOT NULL
, booking_fee NUMERIC NOT NULL
, ticket_price NUMERIC NOT NULL
);
Skeleton for 3-way join:
SELECT bo.booking_id, bo.zdatetime, bo.film
, ci.cinemas_geom
, ci.centroid
, cu.customers_geom
FROM booking bo
JOIN customers cu ON cu.customer_id = bo.customer_id
JOIN cinemas ci ON ci.cinema_id = bo.cinema_id
;
Now, just add the function call, using the results from the skeletton as function arguments (I am not that fluent in GIS, this is only an example to demonstrate the syntax):
SELECT bo.booking_id, bo.zdatetime, bo.film
, st_distance(ci.centroid , cu.customers_geom ) AS the_distance
FROM booking bo
JOIN customers cu ON cu.customer_id = bo.customer_id
JOIN cinemas ci ON ci.cinema_id = bo.cinema_id
;

Where clause in Mutiple table sql joins

TABLES
CREATE TABLE LocalBusiness
(
BusinessID INT NOT NULL PRIMARY KEY,
BusinessName VARCHAR2 (20) NOT NULL,
TypeID INT,
Latitude DECIMAL (10,2),
Longitude DECIMAL (10,2),
Web_address VARCHAR2 (50) NOT NULL,
Postcode VARCHAR2 (10) NOT NULL,
official_rating int,
min_price NUMBER(4,2),
max_price NUMBER(4,2),
FOREIGN KEY (TypeID) REFERENCES LocalBusinessType (TypeID),
CONSTRAINT chk_Officialrating CHECK (official_rating> 0 AND official_rating<6 )
);
CREATE TABLE Address
(
AddressID INT NOT NULL PRIMARY KEY,
BusinessID INT,
AreaID INT,
Address VARCHAR2 (50) NOT NULL,
Postcode VARCHAR2 (10) NOT NULL,
FOREIGN KEY (BusinessID) REFERENCES LocalBusiness (BusinessID),
FOREIGN KEY (AreaID) REFERENCES Area (AreaID)
);
CREATE TABLE Phone
(
PhoneNoID INT NOT NULL PRIMARY KEY,
PhoneNo VARCHAR2 (15) NOT NULL,
BusinessID INT,
Description VARCHAR2 (50) NOT NULL,
FOREIGN KEY (BusinessID) REFERENCES LocalBusiness (BusinessID),
CONSTRAINT PhoneNo_unique UNIQUE (PhoneNo)
);
CREATE TABLE Email
(
EmailID INT NOT NULL PRIMARY KEY,
email_address VARCHAR2 (50) NOT NULL,
BusinessID INT,
Description VARCHAR2 (50) NOT NULL,
FOREIGN KEY (BusinessID) REFERENCES LocalBusiness (BusinessID),
CONSTRAINT email_unique UNIQUE (email_address)
);
CREATE TABLE Area
(
AreaID INT NOT NULL PRIMARY KEY,
AreaName VARCHAR2 (20) NOT NULL,
Region VARCHAR2 (20) NOT NULL
);
SELECT statement:
SELECT
LocalBussiness.BusinessName, Address.Address, Address.Postcode,
Area.AreaName, Area.Region, LocalBusiness.OfficialRating,
LocalBusiness.min_price, LocalBusiness_max_price,
Phone.description, Phone.PhoneNo,
Email.Description, Email.email_address,
LocalBusiness.Web_address
FROM
LocalBusiness
JOIN
Address ON LocalBusiness.BusinessID = Address.BusinessID
JOIN
Area ON Address.AreaID = Area.AreaID
AND LocalBusiness.BusinessID = Address.BusinessID
JOIN
Phone ON Phone.BusinessID = LocalBusiness.BusinessID
JOIN
Email ON Email.BusinessID = LocalBusiness.BusinessID
WHERE
TypeID = '1'
ORDER BY
LocalBusiness.BusinessName ASC;
The where clause in the sql join statement written above seem to be ineffective as the some values for the TypeID return incomplete data while others return no rows at all. How do I go about fixing this?
Yyou repeat a condition
AND LocalBusiness.BusinessID=Address.BusinessID in JOIN Area
Try avoinding this repetition
SELECT LocalBussiness.BusinessName, Address.Address, Address.Postcode,
Area.AreaName, Area.Region, LocalBusiness.OfficialRating,
LocalBusiness.min_price, LocalBusiness_max_price, Phone.description,
Phone.PhoneNo, Email.Description, Email.email_address,
LocalBusiness.Web_address
FROM LocalBusiness
JOIN Address ON LocalBusiness.BusinessID=Address.BusinessID
JOIN Area ON Address.AreaID=Area.AreaID
JOIN Phone ON Phone.BusinessID=LocalBusiness.BusinessID
JOIN Email ON Email.BusinessID=LocalBusiness.BusinessID
WHERE TypeID = '1'
ORDER BY LocalBusiness.BusinessName ASC;
Otherwise check th consistence of your data ..