VB.Net Create a table programatically with foreign key - sql

I'm trying to create a table programmatically via VB.Net and two of the columns should have a primary key. I have the following T-SQL code and I basically need to translate it to SQL so I can execute it programmatically via vb.net :
CREATE TABLE [dbo].[Orders]
(
[OrderID] INT IDENTITY (1, 1) NOT NULL,
[FoodID] INT NOT NULL,
[PriceID] INT NOT NULL,
PRIMARY KEY CLUSTERED ([OrderID] ASC),
CONSTRAINT [FK_Orders_Customer]
FOREIGN KEY ([FoodID]) REFERENCES [dbo].[Customer] ([FoodID])
)
This is what I currently have for my vb.net sql code:
CREATE TABLE customer(OrderID INT NOT NULL,FoodID INT NOT NULL ,PriceID INT NOT NULL
Now I'm not sure how to declare the primary key and how to declare the foreign keys. Also if someone would show an example on how to declare a composite key I would also be grateful (ie. OrderID and FoodID both primary keys). Thank you.

Related

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.

CONSTRAINT to foreign keys to one table - causes error

I am starting to build something like system up to the just cooperate with suggestions coming into the database called ForslagOpslag.
Every time I try to update table with likes, you will see it with this one error:
Update cannot proceed due to validation errors. Please correct the following errors and try again.
SQL71516 :: The referenced table '[dbo].[ForslagOpslag]' contains no
primary or candidate keys that match the referencing column list in
the foreign key. If the referenced column is a computed column, it
should be persisted.
Here is how I built my ForslagOpslagLikes table:
CREATE TABLE [dbo].[ForslagOpslagLikes]
(
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
[getid] INT NOT NULL,
CONSTRAINT [PK_ForslagOpslagLikes]
PRIMARY KEY CLUSTERED ([fk_brugerid], [getid]),
CONSTRAINT [FK_ForslagOpslagLikes_ToGetid]
FOREIGN KEY ([getid])
REFERENCES [dbo].[ForslagOpslag]([Id]),
CONSTRAINT [FK_ForslagOpslagLikes_ToForslagBrugerid]
FOREIGN KEY ([fk_brugerid])
REFERENCES [dbo].[ForslagOpslag]([fk_brugerid])
);
Reason I have both fk_brugerid and getid is for sure me that the user can not vote / like more once!
The way I have built my ForslagOpslag table:
CREATE TABLE [dbo].[ForslagOpslag]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[text] NVARCHAR (MAX) NOT NULL,
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
like this to be my like system do:
ForslagOpslagLikes -> fk_brugerid to ForslagOpslag -> fk_brugerid
ForslagOpslagLikes -> getid to ForslagOpslag -> id
Well - the error seems pretty clear: you're trying to estabslish a foreign key relationship to ForslagOpslag.fk_brugerid here:
CONSTRAINT [FK_ForslagOpslagLikes_ToForslagBrugerid]
FOREIGN KEY ([fk_brugerid])
REFERENCES [dbo].[ForslagOpslag]([fk_brugerid])
but that column is NOT the primary key of that other table - and it's not a UNIQUE constraint either - so you cannot reference that column in a foreign key relationship.
But the column(s) that a foreign key references must be the primary key of that other table - or in SQL Server, it's good enough if there's a UNIQUE constraint on that column. You must ensure that the values you reference in FroslagOpslag only match a single column in that table - otherwise, you cannot establish a foreign key relationship
Try to remove the foreing key in your first table like this
CREATE TABLE [dbo].[ForslagOpslagLikes]
(
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
[getid] INT NOT NULL,
CONSTRAINT [PK_ForslagOpslagLikes]
PRIMARY KEY CLUSTERED ([fk_brugerid], [getid]),
CONSTRAINT [FK_ForslagOpslagLikes_ToGetid]
FOREIGN KEY ([getid])
REFERENCES [dbo].[ForslagOpslag]([Id]),
);
Then you need to add the foreign key in the second table with the primary key with the first table
CREATE TABLE [dbo].[ForslagOpslag]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[text] NVARCHAR (MAX) NOT NULL,
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_ForslagOpslagLikes_ToForslagBrugerid]
FOREIGN KEY ([fk_brugerid])
REFERENCES [dbo].[ForslagOpslagLikes]([fk_brugerid])
);
You sound scandinavian, and Bruger means User (for all the non-scandinavians here).
What you appear to want is a Bruger (User) table, where fk_brugerid in ForslagOpslag is the user who created the record with opretdato being the creation date, and ForslagOpslagLikes is an association table of users who likes the ForslagOpslag with opretdato being the date they clicked on "Like".
CREATE TABLE [dbo].[Bruger]
(
[brugerid] INT IDENTITY (1, 1) NOT NULL,
...,
CONSTRAINT [PK_Bruger]
PRIMARY KEY CLUSTERED ([brugerid])
);
CREATE TABLE [dbo].[ForslagOpslag]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[text] NVARCHAR(MAX) NOT NULL,
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
CONSTRAINT [PK_ForslagOpslag]
PRIMARY KEY CLUSTERED ([Id]),
CONSTRAINT [FK_ForslagOpslag_Bruger]
FOREIGN KEY ([fk_brugerid])
REFERENCES [dbo].[Bruger] ([brugerid])
);
CREATE TABLE [dbo].[ForslagOpslagLikes]
(
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
[getid] INT NOT NULL,
CONSTRAINT [PK_ForslagOpslagLikes]
PRIMARY KEY CLUSTERED ([fk_brugerid], [getid]),
CONSTRAINT [FK_ForslagOpslagLikes_Bruger]
FOREIGN KEY ([fk_brugerid])
REFERENCES [dbo].[Bruger] ([brugerid]),
CONSTRAINT [FK_ForslagOpslagLikes_ForslagOpslag]
FOREIGN KEY ([getid])
REFERENCES [dbo].[ForslagOpslag]([Id])
);

How to link tables in SQL

I have two tables and i want to create a third that references the other two.
stock_group has groupno as primary key
stock_group2s also has groupno as primary key
I want to create table called stock_group3s, with 5 columns:
key int AUTO INCREMENT PRIMARY KEY
groupno INT
group1 [stock_group.groupno]
group2 [stock_group2s.groupno]
name VARCHAR (30)
The two linked columns then must contain only a value that can be found in their referenced tables.
How do set this up? I am using SQL Server 2008 R2 with SQL Server 2008 Management Studio
perhaps you are looking for
create table stock_group (groupno int primary key)
create table stock_group2s(groupno int primary key)
create table stock_group3s
(
IDkey int PRIMARY KEY IDENTITY(1,1)
,groupno INT
,group1 INT
,group2 INT
,name VARCHAR (30)
)
ALTER TABLE stock_group3s WITH NOCHECK ADD CONSTRAINT FK_stock_group3s_stock_group FOREIGN KEY(group1)
REFERENCES stock_group (groupno)
ALTER TABLE stock_group3s WITH NOCHECK ADD CONSTRAINT FK_stock_group3s_stock_group2s FOREIGN KEY(group2)
REFERENCES stock_group2s (groupno)

SQL Management Studio 2012 Foreign Key Is A Mess

I am trying to add a foreign key to a table. I have created two tables.
CREATE TABLE madeupbusiness.staff
(
staffnum int NOT NULL,
forename varchar(30) NOT NULL,
surname varchar(30) NOT NULL,
meeting int NOT NULL,
PRIMARY KEY (staffnum),
)
GO
meeting should use the PK from from the meeting table to create a FK :
CREATE TABLE madeupbusiness.meeting
(
meetingnum int NOT NULL,
room varchar(30) NOT NULL,
PRIMARY KEY (meetingnum),
)
GO
To create the foreign key I run this query
ALTER TABLE madeupbusiness.staff
WITH CHECK
ADD CONSTRAINT FK_staff_meetingnum FOREIGN KEY (meetingnum)
REFERENCES madeupbusiness.meeting(meetingnum)
ON DELETE CASCADE
ON UPDATE CASCADE
;
GO
The query runs but when I create a database diagram there is a square loop the staff table from the staffnum key back onto it. Sorry but I don't really know how to describe it. There is no relationship between the two tables. What am I doing wrong?
I have tried to add the relationship from design view but the foreign key table is greyed out.
If you can rebuild the Table do this:
CREATE TABLE madeupbusiness.meeting
(meetingnum int NOT NULL PRIMARY KEY REFERENCES madeupbusiness.meeting(YourColumnYouWantItShouldBeReferenced),
room varchar(30) NOT NULL);
GO

SQL Multiple Foreign Keys as Primary Keys

If I declare the table below does it implicitly imply that both the foreign keys make a unique primary key or do I need to do something more to make both attributes as a primary key?
CREATE TABLE Report_has_Items
(
ReportID int REFERENCES Report(ReportID) NOT NULL,
ItemID int REFERENCES Item(ItemID) NOT NULL
)
Essentially both attributes which are foreign keys from other tables, together would form a unique key.
No it doesn't. The above table has no primary key. If you want to use the fields as a primary key use:
CREATE TABLE Report_has_Items(
ReportID int REFERENCES Report(ReportID) NOT NULL,
ItemID int REFERENCES Item(ItemID) NOT NULL,
PRIMARY KEY (ReportID, ItemID)
)
or something similar depending on your sql dilect.
Let's name our constraints, eh?
CREATE TABLE dbo.Report_has_Items(
ReportID int NOT NULL,
CONSTRAINT [FK_RHI_Report] (ReportId) REFERENCES dbo.Report(ReportID),
ItemID int NOT NULL,
Constraint [FK_RHI_Item] (ItemId) REFERENCES dbo.Item(ItemID),
CONSTRAINT [PK_RHI] PRIMARY KEY (ReportID, ItemID)
)
I am not sure i understand your question completely but i assume you are trying to create a composite primary key (primary key with more than one attribute). You could do the following.
CREATE TABLE Report_has_Items(
ReportID int references Report(ReportID),
ItemID int references Item(ItemID),
PRIMARY KEY (ReportID , ItemID )
);
Note:The pair (ReportID , ItemID ) must then be unique for the table and neither value can be NULL.
Here is a very useful link for SQL Queries