Create a many to many relation and give each relation an object - database

I am writing a query to create a database in SQL server 2008 R2. I plan to use it with entity framework in a mvc3 application
I have users, games and highscores.
What I want ot do is this:
I want to create a many-to-many relationship between users and games.
Each User can have multiple games and each game can have multiple users.
and each relation user-game has 1 high score.
So far I created the users, games, highscores tables:
CREATE TABLE Users
(
UserId INT IDENTITY(1,1),
FirstName VARCHAR(64) NOT NULL,
LastName VARCHAR(64) NOT NULL,
Email VARCHAR(200) NOT NULL,
CreatedDate DateTime NULL,
PhoneNumber VARCHAR(32) NULL,
Password VARCHAR(64),
CONSTRAINT pk_users_userid PRIMARY KEY(UserId)
)
CREATE TABLE Games
(
GameId INT IDENTITY(1,1),
Url VARCHAR(64) NOT NULL,
CONSTRAINT pk_gamess_gameid PRIMARY KEY(GameId)
)
CREATE TABLE Highscores
(
HighscoreId INT IDENTITY(1,1),
Value INT NOT NULL,
CONSTRAINT pk_surveyors_surveyorid PRIMARY KEY(HighscoreId)
)
What is the best way to create the many-to-many user-game relation and give each relation one high score? should I create a 4th table to hold the relation? And if I do so will I be able to use the database with Entity framework in an MVC3 application or would that complicate it?
Thank you
Additional note: I am planning to use this database with entity framework in a MVC 3 web application.

CREATE TABLE Users (
UserId INT IDENTITY(1,1),
FirstName VARCHAR(64) NOT NULL,
LastName VARCHAR(64) NOT NULL,
Email VARCHAR(200) NOT NULL,
CreatedDate DateTime NULL,
PhoneNumber VARCHAR(32) NULL,
Password VARCHAR(64),
CONSTRAINT pk_users_userid PRIMARY KEY(UserId)
)
CREATE TABLE Games (
GameId INT IDENTITY(1,1),
Url VARCHAR(64) NOT NULL,
CONSTRAINT pk_gamess_gameid PRIMARY KEY(GameId)
)
CREATE TABLE Highscores (
HighscoreId INT IDENTITY(1,1),
UserID Int,
GameID Int,
Value INT NOT NULL,
CONSTRAINT pk_surveyors_surveyorid PRIMARY KEY(HighscoreId)
)
ALTER TABLE [dbo].[Highscores] ADD CONSTRAINT [FK_Highscores_Games] FOREIGN KEY([GameID])
ALTER TABLE [dbo].[Highscores] ADD CONSTRAINT [FK_Highscores_Users] FOREIGN KEY([UserID])

Related

How to organize common columns to a single table?

I'm very new to database designing and I'm creating a small project to understand it better, I'm trying to come up with a new school crm. I started with the below schema:
create table student(
id int not null,
firstname varchar(100),
lastname varchar(100),
PRIMARY key (id)
);
create table address(
id int not null,
street varchar(30) not null,
city varchar(30) not null,
PRIMARY KEY (id)
);
-- they have own roles for app
create table guardians(
id int not null,
firstname varchar(100),
lastname varchar(100),
primary key (id)
);
-- teacher have own roles
create table teacher(
id int not null,
firstname varchar(100),
lastname varchar(100),
PRIMARY key (id)
)
guardians and teachers will have password for login the web portal. The reason why I created separate table is mainly because teachers might have column's like salary, schoolId etc in the future. But now if I look at the schema here, mostly the firstName, lastname is common for all student, teacher and guardians.
How can I have a common table for such repeatable field names? Or this design is good? Also I wanted to have another table ROLE which going to give permissions at app level to update/insert certain tables. Not sure how can I design it as well.
The schema you have planned will end up having and lot of redundancies in different tables (like firstName and lastName as you have described for each of the three tables). Also, if in future a new role turns up you will be creating new table and leading to more redundancy.
I would suggest it would we better if you create one table for user and define role of the user in that table.
e.g.:
create table user(
u_id int not null,
firstname varchar(100),
lastname varchar(100),
role varchar(100),
PRIMARY key (id)
);
You can maintain role specific data in different table and can be accessed via primary key of user table.
e.g.:
create table teacher(
t_id int not null,
u_id int,
Salary int,
qualification varchar(100),
PRIMARY key (id),
FOREIGN KEY (u_id) REFERENCES user(u_id)
)
Having a role column in user table will solve your second problem as well.

Can't create the tables because the primary keys used as foreign keys in another table

Create Table Customer
(
Cus_id Varchar2(10) NOT NULL Primary Key,
Cus_FirstName Varchar2(20) NOT NULL,
Cus_LastName Varchar2 (20) NOT NULL,
Cus_Address Varchar2(25) NOT NULL,
Cus_City_State_Zip Varchar2(30) NOT NULL
);
Create Table Order_
(
Order_id Varchar2(10) NOT NULL Primary Key,
Order_Date Varchar2(12) NOT NULL,
Order_Status Varchar(12) NOT NULL
);
Create Table Item
(
Item_id Varchar2(10) NOT NULL Primary Key,
Item_Name Varchar2(20) NOT NULL,
Item_Price Varchar2(10) NOT NULL
);
Create Table CustomerOrderItem
(
Quantity Varchar2(8) NOT NULL,
Cus_id Varchar(10) NOT NULL Primary Key,
Order_id Varchar(10) NOT NULL Primary Key,
Item_id Varchar(10) NOT NULL Primary Key,
Foreign Key(Cus_id) References Customer(Cus_id),
Foreign Key(Oreder_id) References Order_(Order_id),
Foreign Key(Item_id) References Item(Item_id)
);
This code is a customer table with repeated orders and multiple items for one order. When I try to insert values into the table and create them. I created the fourth table due to their dependency and put three primary keys there as primary keys and foreign keys. It does not let me create the tables saying because the primary keys used as foreign keys in another table, therefore I need to drop them first to create the tables.
Your data schema neither matches what you describe, nor is a correct syntax for SQL Server. Putting aside the bad design, this is what you are trying to do:
Create Table Customer ( Cus_id Varchar(10) NOT NULL Primary Key,
Cus_FirstName Varchar(20) NOT NULL,
Cus_LastName Varchar (20) NOT NULL,
Cus_Address Varchar(25) NOT NULL,
Cus_City_State_Zip Varchar(30) NOT NULL );
Create Table Order_ ( Order_id Varchar(10) NOT NULL Primary Key,
Order_Date Varchar(12) NOT NULL,
Order_Status Varchar(12) NOT NULL );
Create Table Item ( Item_id Varchar(10) NOT NULL Primary Key,
Item_Name Varchar(20) NOT NULL,
Item_Price Varchar(10) NOT NULL );
Create Table CustomerOrderItem ( Quantity Varchar(8) NOT NULL,
Cus_id Varchar(10) NOT NULL,
Order_id Varchar(10) NOT NULL,
Item_id Varchar(10) NOT NULL,
constraint PK_CustomerOrderItem primary key (cus_id, order_id, item_id),
constraint FK_COI_Customer Foreign Key(Cus_id) References Customer(Cus_id),
constraint FK_COI_Order Foreign Key(Order_id) References Order_(Order_id),
constraint FK_COI_Item Foreign Key(Item_id) References Item(Item_id) );
Check Northwind sample database for a better sample, and for even a better one check AdventureWorks sample database as starters.
the Error message you got ORA-02449 is due to trying to drop a table that is already referenced as primary key in CustomerOrderItem table ,to solve this issue drop the CustomerOrderItem table first then drop the other tables afterwards.
Good luck.

SQL create table using code and populate with code

I'm working on an assignment and have created my code on NotePad++ to then copy over to SSMS, however when I create a table it brings me to the default view which is manually entering the column names and data. I want to just paste my created code into the database to create the table. How do I go about this?
Also my prof has provided data to populate my tables but I can't seem to figure out where I paste his INSERT INTO data into?
Also, for some reason I attempted to create a new query in the database i created for the assignment and pasted the code into that, but the tables don't show up even if I execute them in the Tables drop down.
Code for notepad++
CREATE TABLE tblMajors
(
MajorCode varchar(10) PRIMARY KEY NOT NULL,
MajorDescription varchar(MAX) NOT NULL,
)
CREATE TABLE tblInstructors
(
InstructorNumber int PRIMARY KEY NOT NULL,
InstructorFirst varchar(50) NOT NULL,
InstructorLast varchar(50) NOT NULL,
ContractStatus varchar(10) NOT NULL,
PhoneNumber bigint NOT NULL,
)
CREATE TABLE tblStudents
(
StudentNumber int PRIMARY KEY NOT NULL,
StudentFirst varchar(20) NOT NULL,
StudentLast varchar(20) NOT NULL,
MajorCode varchar(10) FOREIGN KEY REFERENCES tblMajors (MajorCode),
)
CREATE TABLE tblCourses
(
CourseCode varchar(10) PRIMARY KEY NOT NULL,
CourseDescription varchar(MAX) NOT NULL,
)
CREATE TABLE tblGrades
(
StudentNumber bigint FOREIGN KEY REFERENCES tblStudents (StudentNumber),
CourseCode varchar(10) FOREIGN KEY REFERENCES tblCourses (CourseCode),
Grade int NOT NULL,
IntructorNumber int FOREIGN KEY REFERENCES tblInstructors (IntructorNumber),
PRIMARY KEY (StudentNumber, CourseCode)
)

How can I make one table depend on another in SQL Server?

I have the following tables that I created in SQL Server:
CREATE TABLE [dbo].[Application] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Name] NVARCHAR (MAX) NULL,
CONSTRAINT [PK_dbo.Application] PRIMARY KEY CLUSTERED ([Id] ASC)
);
CREATE TABLE [dbo].[Account] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Name] NVARCHAR (MAX) NULL,
CONSTRAINT [PK_dbo.Account] PRIMARY KEY CLUSTERED ([Id] ASC)
);
Is there a way I can change these so that there's a link to the
account table inside the application table. A link that makes it
not possible to delete an application entry if there is an
account for that application? Sorry if this is a basic question
but I only know how to use the designer and I am not sure how I
can code this in SQL.
Add a foreign key relationship between the two tables. In your case you would want to add another int type column to the Account table called Application_Id. Then add the foreign relationship between Application_Id and Id on the Application table. I also suggest possibly changing Id on the Application table to Application_Id
CREATE TABLE [dbo].[Application] (
[Application_Id] INT IDENTITY (1, 1) NOT NULL,
[Name] NVARCHAR (MAX) NULL,
CONSTRAINT [PK_dbo.Application] PRIMARY KEY CLUSTERED ([Application_Id] ASC)
);
CREATE TABLE [dbo].[Account] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Application_Id] INT,
[Name] NVARCHAR (MAX) NULL,
CONSTRAINT [PK_dbo.Account] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT fk_AccountApps FOREIGN KEY (Application_Id)
REFERENCES Application(Application_Id)
);
SQL Fiddle
W3 Schools Foreign Key
Your problem can be solved using foreign key concept.
http://en.wikipedia.org/wiki/Foreign_key

How can I create this trigger for Microsoft SQL Server?

I have this limitation I have to implement server-side (in the database). Normally I'd do this on the client side, but I'd figure why not learn the server aspect. :p
I don't want my Clients to be able to rent a Movie from the XXX genre if they are under 18.
Here is the script I used to generate the tables:
-- =============================================
-- Sergio's Lab Tests MWA HA HA
-- =============================================
use AlquilerPeliculas
create table Client
(
ID int primary key not null identity(1,1),
Address nvarchar(1024) not null,
Phone nvarchar(256) not null,
NIT nvarchar(32) not null
)
go
create table Genre
(
ID int primary key not null identity(1,1),
Name nvarchar(256)
)
go
create table Movie
(
ID int primary key not null identity(1,1),
Name nvarchar(256) not null,
IDGenre int foreign key references Genre(ID)
)
go
create table Natural
(
IDCliente int primary key references Cliente(ID),
Age as datediff(d, FechaDeNacimiento,getdate())/365.00,
Nombre nvarchar(1024) not null,
ApellidoPaterno nvarchar(512) not null,
FechaDeNacimiento datetime,
Sexo varchar(1) not null check(Sexo='M' or Sexo='F')
)
go
create table Alquiler
(
ID int primary key not null identity(1,1),
FechaDeAlquiler datetime,
Total nvarchar(20) not null,
IDClient int foreign key references Client(ID)
)
go
create table Ejemplar
(
ID int primary key not null identity(1,1),
NumeroDeEjemplar nvarchar(256) not null,
Descripcion nvarchar(1024),
IDFormato int foreign key references Formato(ID),
IDPelicula int foreign key references Pelicula(ID)
)
go
create table DetalleAlquiler
(
ID int primary key not null identity(1,1),
IDEjemplar int foreign key references Ejemplar(ID),
IDAlquiler int foreign key references Alquiler(ID),
PrecioDeAlquiler nvarchar(128),
FechaDevolucion datetime,
FechaDevolucionProgramada datetime
)
I asked a friend what I should use and he said a Trigger, but it's my understanding that a trigger is a function that's run when the triggers conditions are met, right? If I used a trigger I'd have to insert then delete a naughty record right?
Thanks for the help.
Read all about triggers here
They come in many flavors, they can run before every insert / after every update and so on. The triggering of the trigger is a blanket action, if you have a BEFORE trigger, it will always run before.
Then, if you want to do any filtering or error handling, for example, only run a bit of code if a particular column has a particular value, you include that inside the trigger (in conditional code).
Generally, I recommend against using triggers, they can often make locking more complicated and are "hidden" in a place no one tends to look (which make them very hard to debug).
Another approach you can take DB-wise, it have particular stored procs that you call, instead of calling tables directly, eg: spRentMovie.

Resources