SQL Server : create error how to write database name with the table name - sql

CREATE DATABASE agom COLLATE Arabic_CI_AS
CREATE TABLE Branches
(
ID INT PRIMARY KEY NOT NULL IDENTITY,
NAME VARCHAR(255) NOT NULL
)
CREATE TABLE agom.Brands
(
ID INT PRIMARY KEY NOT NULL IDENTITY,
NAME VARCHAR(255) NOT NULL
)
CREATE TABLE agom.Work_Order
(
NUMBER INT NOT NULL,
BRANCHID INT NOT NULL,
BRANDID INT NOT NULL,
WDATE DATE NOT NULL,
REPAIRSTATUS VARCHAR(255),
REPAIRCOST VARCHAR(255),
REMARK VARCHAR(500),
PRIMARY KEY (NUMBER,BRANCHID,BRANDID)
)
CREATE TABLE agom.Profiles
(
ID INT PRIMARY KEY NOT NULL IDENTITY,
USERNAME VARCHAR(25) NOT NULL,
PASS VARCHAR(25) NOT NULL
)
ALTER TABLE agom.Work_Order
ADD CONSTRAINT branchfk
FOREIGN KEY (BRANCHID) REFERENCES Branches(ID)
ALTER TABLE agom.Work_Order
ADD CONSTRAINT brandfk
FOREIGN KEY (BRANDID) REFERENCES Brands(ID)
I get an error that cannot create table
I try to write database name with the table name db.tablename but it's not working
I need to create the database then create the tables and its constraints but I don't know where is the error.I am a sql noob

It's never Database.Table.
It's either Table, or Schema.Table, or Database.Schema.Table, or Server.Database.Schema.Table.
You probably just want to insert USE agom right after create database, and then only refer to tables by name.
Alternatively, you can refer to your tables as agom.dbo.Work_Order, dbo being the default database schema.
See Using Identifiers As Object Names for general reference.

Related

Can we update a record that is defined as a foreign key of a unique record define in a different table?

I am new to PostgreSQL and how i can update the records while they are related with a foreign key definition.
I am getting an error and that would be great if you can guide me with any hints
Let's say we have two different tables like below :
CREATE TABLE IF NOT EXISTS student
(
id_num VARCHAR(40) NOT NULL REFERENCES registered(student_id),
first_name VARCHAR(32) NOT NULL,
last_name VARCHAR(32) NOT NULL,
birthdate DATE NOT NULL,
PRIMARY KEY(id_num)
);
CREATE TABLE IF NOT EXISTS registered
(
student_id VARCHAR(40) NOT NULL UNIQUE,
paid_tuition BOOL NOT NULL,
PRIMARY KEY(paid_tuition)
);
Based on my understating i need to fill the registered table and then try to insert values to the student table that their id match the student_id value in registered table.
But when I try it I get the following error?
Any idea or recommendation?
Message:"update or delete on table "registered" violates foreign key
constraint "student_id_num_id_fkey" on table "student"",
Detail:"Key (id_num)=(idNum-1) is still referenced from table
"student".", Hint:"", Position:0, InternalPosition:0,
InternalQuery:"", Where:"", SchemaName:"", TableName:"student",
ColumnName:"", DataTypeName:"",
ConstraintName:"student_id_num_id_fkey", File:"ri_triggers.c",
Line:2490, Routine:"ri_ReportViolation"}
seems like you are linking tables in opposite direction , to me it makes more sense that "registered" table has been linked to student table by fk studentid .
also in your "student" table definition you are saying that column "id" is primary key while no "id" column has been declared.
so here is what I mean:
CREATE TABLE IF NOT EXISTS student
(
id_num VARCHAR(40) NOT NULL REFERENCES registered(student_id),
first_name VARCHAR(32) NOT NULL,
last_name VARCHAR(32) NOT NULL,
birthdate DATE NOT NULL,
PRIMARY KEY(id_num)
);
CREATE TABLE IF NOT EXISTS registered
(
student_id VARCHAR(40) NOT NULL REFERENCES student(id_num)
paid_tuition BOOL NOT NULL,
PRIMARY KEY(id_num)
);

Creating SQL database. with multiple primary and foreign keys

I'm currently working through an assignment that is asking me to create a SQL database using SQL Server Express. This is what it's asking for:
CREATE DATABASE USING SQL
And this is the code I have tried running;
CREATE DATABASE db_Library
Go
USE db_Library
CREATE TABLE tbl_library_branch
(
library_branch_branch_id INT PRIMARY KEY NOT NULL IDENTITY (1,1),
library_branch_branch_name VARCHAR(50) NOT NULL,
library_branch_address VARCHAR(50) NOT NULL
);
CREATE TABLE tbl_publisher
(
library_publisher_publisher_name VARCHAR(50) PRIMARY KEY NOT NULL,
library_publisher_address VARCHAR(50) NOT NULL,
library_publisher_phone INT NOT NULL
);
CREATE TABLE tbl_books
(
library_books_book_id INT PRIMARY KEY NOT NULL IDENTITY (1,1),
library_books_title VARCHAR(50) NOT NULL,
library_books_publisher_name VARCHAR(50) NOT NULL CONSTRAINT fk_library_books_publisher_name FOREIGN KEY REFERENCES tbl_publisher(library_publisher_publisher_name) ON UPDATE CASCADE ON DELETE CASCADE
);
CREATE TABLE tbl_book_authors
(
library_book_authors_book_id INT NOT NULL CONSTRAINT fk_library_book_authors_book_id FOREIGN KEY REFERENCES tbl_books(library_books_book_id) ON UPDATE CASCADE ON DELETE CASCADE,
library_book_authors_author_name VARCHAR(50) NOT NULL
);
CREATE TABLE tbl_book_copies
(
library_book_copies_book_id INT NOT NULL CONSTRAINT fk_library_book_copies_book_id FOREIGN KEY REFERENCES tbl_books(library_books_title),
library_book_copies_branch_id INT NOT NULL,
library_book_copies_number_of_copies INT NOT NULL
);
CREATE TABLE tbl_book_loans
(
library_book_loans_book_id INT NOT NULL,
library_book_loans_branch_id INT NOT NULL,
library_book_loans_card_no INT NOT NULL,
library_book_loans_date_out INT NOT NULL,
library_book_loans_date_due INT NOT NULL
);
CREATE TABLE tbl_borrower
(
library_borrower_card_no INT PRIMARY KEY NOT NULL IDENTITY (1,1),
library_borrower_name VARCHAR(50) NOT NULL,
library_borrower_address VARCHAR(50) NOT NULL,
library_borrower_phone VARCHAR(50) NOT NULL
);
Using the library "Books" as an example it looks like I need to have BoodID as a primary key and Title as a primary key, but you can't have more than one primary key per table..
Then I have to take BookID from the Book_Copies table and the Book_Loans table connect to the primary key of Title in Books?
I'm beyond stuck at this point and would appreciate any resources you think could help.
There is no need to be so verbose. I think you want something more like this (for two tables):
CREATE TABLE tbl_publisher (
publisher_id int IDENTITY(1, 1) PRIMARY KEY,
publisher_name VARCHAR(50) NOT NULL UNIQUE,
address VARCHAR(50) NOT NULL,
phone INT NOT NULL
);
CREATE TABLE books (
book_id INT IDENTITY (1,1) PRIMARY KEY,
title VARCHAR(50) NOT NULL UNIQUE,
publisher_id INT NOT NULL CONSTRAINT fk_books_publisher__id FOREIGN KEY REFERENCES tbl_publisher(publisher_id) ON UPDATE CASCADE ON DELETE CASCADE
);
Notes:
Stick with synthetic primary keys for all the tables. That is, identity columns.
Other columns can be declared to be unique. That is fine.
I type quite fast. And yet I would quickly wary of typing library_book_ over and over. Such repetition just makes it harder to write and read queries.

Can't figure out how to make a subquery

CREATE TABLE TBLTeams
(
teamnm varchar(30) NOT NULL,
teamid varchar(10),
rondenm varchar(10)
primary key(teamnm)
)
CREATE TABLE TBLWedstrijd
(
thuisteamnm varchar(30) NOT NULL,
uitteamnm varchar(30) NOT NULL,
wedstrijdid varchar(10)
primary key(wedstrijdid)
)
alter table TBLWedstrijd add foreign key (thuisteamnm) references TBLTeams(teamnm)
alter table TBLWedstrijd add foreign key (uitteamnm) references TBLTeams(teamnm)
CREATE TABLE TBLUitslag
(
thuisteamnm varchar(30) NOT NULL,
uitteamnm varchar(30) NOT NULL,
wedstrijdid varchar(10) NOT NULL,
uitteampunt int,
thuisteampunt int
primary key(thuisteamnm)
)
alter table TBLUitslag add foreign key (wedstrijdid) references TBLWedstrijd(wedstrijdid)
If I update teamnm in TBLTeams how can I update reference in TBLWedstrijd uitteamnm. I know its a subquery but I really dont know how.
You're going about it a bit wrong. If you're going to change the teamname, you shouldn't use it as a key (Since that will break all references).
You'll want to reference their IDs from the TBLWedstrijd instead of using their name.
So your statements will become:
CREATE TABLE TBLWedstrijd
(
wedstrijdid varchar(10),
thuisteamid varchar(10) NOT NULL,
uitteamid varchar(10) NOT NULL,
primary key(wedstrijdid)
)
alter table TBLWedstrijd add foreign key (thuisteamid) references TBLTeams(teamid)
alter table TBLWedstrijd add foreign key (uitteamid) references TBLTeams(teamid)
The same is valid for your table TBLUitslag, you should only reference TBLWedstrijd, since that one already holds the info about which teams are playing. Not to mention, the score is pretty much part of a game anyway so it doesn't make a lot of sense to seperate those into 2 tables. So that becomes:
CREATE TABLE TBLWedstrijd
(
wedstrijdid varchar(10),
thuisteamid varchar(10) NOT NULL,
uitteamid varchar(10) NOT NULL,
uitteampunt int,
thuisteampunt int
primary key(wedstrijdid)
)
This is called "table normalisation" if you wanted to google some stuff for more info about it.

PSQL/SQL constraint to insert or delete

I have these tables:
user
id
permission
id
user_id
old_permission
user_id
value
Values:
user
id
1
2
3
permission
id user_id
1 1
2 2
old_permission
user_id value
1 f
2 f
3 t
As the table names suggest, I am migrating from a legacy permissions system. What I want to do is:
When old_permission.value is 't', i want any matching rows in permission for the user to be deleted. So if user 3 had an entry in the permission table, it would be deleted if its old_permission.value = 't'.
I also want to create a row in the permission table if the associated old_permission.value = 'f'
How can I create a constraint like this?
I would create a Stored Procedure that refreshes the Permission table based on the Old_Permission table:
CREATE PROCEDURE RefreshPermissions()
AS
BEGIN
DELETE
Permission
WHERE
EXISTS
(SELECT
NULL
FROM
Old_Permission
WHERE
Permission.user_id = Old_Permission.user_id
AND Old_Permission.Value = 't');
INSERT INTO
Permission (user_id)
SELECT
Old_Permission.user_id
FROM
Old_Permission
LEFT JOIN Permission ON Old_Permission.user_id = Permission.user_id
WHERE
Old_Permission.Value = 'f'
AND Permission.user_Id IS NULL;
END;
Then I would suggest using triggers on the Old_Permission table to modify the Permission table as needed. Something like this:
CREATE TRIGGER
TR_Old_Permission
AFTER INSERT OR UPDATE OR DELETE ON
Old_Permission
EXECUTE PROCEDURE
RefreshPermissions();
The PL/SQL is part of Oracle. And Constraints are part of SQL not PL/SQL. You cannot create constraints like this. You need to write some code, could be procedures and/or triggers that would delete and insert according to your logic. Basically, while migrating, and I do not know what exactly you are doing to migrate and how, you loop through records then delete and insert records according to your conditions/filters. It is hard to suggest anything more as I need more details to decide how and what to do exactly in your case.
i am not able to understand the exact problem of yours,for that i thought of making u to understand the concept of the constraints in sql,including its defination and types.
Constraints are used to limit the type of data that can go into a table.
Constraints can be specified when a table is created (with the CREATE TABLE statement) or after the table is created (with the ALTER TABLE statement).
types of constraints:
•NOT NULL
•UNIQUE
•PRIMARY KEY
•FOREIGN KEY
•CHECK
•DEFAULT
Explanitation of the types of constraints with small examples for each:-
SQL NOT NULL Constraint
•The NOT NULL constraint enforces a column to NOT accept NULL values.
•The NOT NULL constraint enforces a field to always contain a value. This means that you
cannot insert a new record, or update a record without adding a value to this field.
•The following SQL enforces the "P_Id" column and the "LastName" column to not accept NULL
values:
•CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
SQL UNIQUE Constraint
The UNIQUE constraint uniquely identifies each record in a database table.
SQL UNIQUE Constraint on CREATE TABLE
The following SQL creates a UNIQUE constraint on the "P_Id" column when the "Persons" table
is created:
MySQL:
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
UNIQUE (P_Id)
)
SQL Server / Oracle / MS Access:
CREATE TABLE Persons
(
P_Id int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
To allow naming of a UNIQUE constraint, and for defining a UNIQUE constraint on multiple
columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName)
)
SQL UNIQUE Constraint on ALTER TABLE
To create a UNIQUE constraint on the "P_Id" column when the table is already created,
use the following SQL:
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Persons
ADD UNIQUE (P_Id)
To allow naming of a UNIQUE constraint, and for defining a UNIQUE constraint on multiple
columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Persons
ADD CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName)
To DROP a UNIQUE Constraint
To drop a UNIQUE constraint, use the following SQL:
MySQL:
ALTER TABLE Persons
DROP INDEX uc_PersonID
SQL Server / Oracle / MS Access:
ALTER TABLE Persons
DROP CONSTRAINT uc_PersonID
SQL PRIMARY KEY Constraint
The PRIMARY KEY constraint uniquely identifies each record in a database table.
Primary keys must contain unique values.
A primary key column cannot contain NULL values.
Each table should have a primary key, and each table can have only ONE primary key.
SQL PRIMARY KEY Constraint on CREATE TABLE
The following SQL creates a PRIMARY KEY on the "P_Id" column when the "Persons" table is
created:
MySQL:
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (P_Id)
)
SQL Server / Oracle / MS Access:
CREATE TABLE Persons
(
P_Id int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on
multiple columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)
)
SQL FOREIGN KEY Constraint on CREATE TABLE
The following SQL creates a FOREIGN KEY on the "P_Id" column when the "Orders" table is
created:
MySQL:
CREATE TABLE Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (O_Id),
FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)
)
SQL Server / Oracle / MS Access:
CREATE TABLE Orders
(
O_Id int NOT NULL PRIMARY KEY,
OrderNo int NOT NULL,
P_Id int FOREIGN KEY REFERENCES Persons(P_Id)
)
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on
multiple columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
CREATE TABLE Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (O_Id),
CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
)
SQL CHECK Constraint on CREATE TABLE
The following SQL creates a CHECK constraint on the "P_Id" column when the "Persons" table
is created. The CHECK constraint specifies that the column "P_Id" must only include integers greater than 0.
MySQL:
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CHECK (P_Id>0)
)
SQL DEFAULT Constraint
The DEFAULT constraint is used to insert a default value into a column.
SQL DEFAULT Constraint on CREATE TABLE
The following SQL creates a DEFAULT constraint on the "City" column when the "Persons"
table is created:
My SQL / SQL Server / Oracle / MS Access:
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255) DEFAULT 'Sandnes'
)
The DEFAULT constraint can also be used to insert system values, by using functions like
GETDATE():
CREATE TABLE Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
OrderDate date DEFAULT GETDATE()
)
above explination is in general format of using constraints,hope it may help you to overcome from your problem...........................

SQL SMS - Error - There is already an object named "genre" in the database

I'm trying to create a hypothetical videostore database and this error message comes up everytime I execute this query:
DROP DATABASE videostore
CREATE DATABASE videostore
CREATE TABLE genre
(
genre_id INT NOT NULL PRIMARY KEY IDENTITY,
genre_name VARCHAR(15) NOT NULL
);
CREATE TABLE classification
(
rating VARCHAR(2) NOT NULL CONSTRAINT classification_pk PRIMARY KEY,
description VARCHAR(100) NOT NULL,
minimum_age INT NULL,
);
CREATE TABLE format
(
format_id INT NOT NULL CONSTRAINT format_pk PRIMARY KEY IDENTITY,
format_name VARCHAR(8) NOT NULL,
purchase_cost FLOAT NOT NULL
);
CREATE TABLE rental_cost
(
rental_cost_id INT NOT NULL CONSTRAINT rental_cost_pk PRIMARY KEY IDENTITY,
rental_name VARCHAR(15) NOT NULL,
rental_cost FLOAT NOT NULL,
rental_days TINYINT NOT NULL
);
CREATE TABLE customer
(
customer_id INT NOT NULL CONSTRAINT customer_pk PRIMARY KEY IDENTITY,
first_name VARCHAR(20) NOT NULL,
surname VARCHAR(20) NOT NULL,
dob DATETIME NOT NULL,
home_address VARCHAR(50) NOT NULL,
contact_number VARCHAR(10) NOT NULL,
referrer_id INT NULL FOREIGN KEY REFERENCES customer(customer_id),
);
CREATE TABLE movie
(
movie_id INT NOT NULL CONSTRAINT movie_pk PRIMARY KEY IDENTITY,
movie_name VARCHAR(40) NOT NULL,
year SMALLINT NOT NULL,
duration SMALLINT NULL,
descrip VARCHAR(120) NULL,
classification VARCHAR(2) NOT NULL FOREIGN KEY REFERENCES classification(rating),
rental_cost_id INT NOT NULL FOREIGN KEY REFERENCES rental_cost(rental_cost_id),
);
CREATE TABLE copy
(
copy_id INT NOT NULL CONSTRAINT copy_pk PRIMARY KEY IDENTITY,
movie_id INT NOT NULL FOREIGN KEY REFERENCES movie(movie_id),
format_id INT NOT NULL FOREIGN KEY REFERENCES format(format_id),
);
CREATE TABLE rental
(
rental_id INT NOT NULL CONSTRAINT rental_pk PRIMARY KEY IDENTITY,
copy_id INT NOT NULL FOREIGN KEY REFERENCES copy(copy_id),
customer_id INT NOT NULL FOREIGN KEY REFERENCES customer(customer_id),
rental_date DATETIME NOT NULL,
return_date DATETIME NULL
);
CREATE TABLE genre_movie
(
genre_id INT NOT NULL FOREIGN KEY REFERENCES genre(genre_id),
movie_id INT NOT NULL FOREIGN KEY REFERENCES movie(movie_id),
CONSTRAINT genre_movie_pk PRIMARY KEY (genre_id, movie_id)
);
(Sorry it's not in the correct format for reading a script with ease, I just really couldn't work out how to do that.)
Basically when I execute the SQL script it tells me that the object 'genre' already exists, but I can't see it anywhere else in my code.
And the table shouldn't already exist because I drop the database each time the script is executed right?
Sidenote - if there's a better way to make it so the database is dropped only if it exists please help me with that also.
Appreciate it.
I think you need to add USE videostore after the CREATE DATABASE videostore. Otherwise you are creating tables in whatever database you are currently in.
I think you are executing this in the context of the master database. If you check it you will probably see all your tables are actually in master.
Change the first part to this:
DROP DATABASE videostore
CREATE DATABASE videostore
USE videostore
CREATE TABLE genre
It's generally best to execute sql statements when required - try:
DROP DATABASE videostore
GO
CREATE DATABASE videostore
GO
USE videostore
CREATE TABLE genre
(
genre_id INT NOT NULL PRIMARY KEY IDENTITY,
genre_name VARCHAR(15) NOT NULL
);
GO
etc.