How to link tables in SQL - 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)

Related

sql server 2019 foreign key on multiple columns from different tables

so i have to create three tables :
the first one is :
create table TblProf(profId int IDENTITY(1,1) PRIMARY KEY
,profName nvarchar(50)
,profUsername nvarchar(50));
and the second one is
create table TblStudent(studentId int IDENTITY(1,1) PRIMARY KEY
,studentName nvarchar(50)
,studentUsername nvarchar(50));
and i want to create the third table which should have two foreign keys the first one is profID from the table TblProf and the secaond one is studentId from the table TblStudent.
so it's two foreign keys from two diffrent tables ,is it possible ?
if so how should i create it?
This is called a bridge table
CREATE TABLE bridge(
refprofId int FOREIGN KEY REFERENCES TblProf(profId ),
refstudentId int FOREIGN KEY REFERENCES TblStudent(PersonID)
,PRIMARY KEY(refprofIdm,refstudentId));
you can add more columns, when the bridge has its own propertoes

How to make Primary Key in Sql Server Using Alter Statement?

I have forgot create a primary key for my table. Now I want to update the DocDay_Id column and make it the primary key. How can I do it?
My code is below.
I tried this syntax but it is not correct.
ALTER TABLE DoctorDays
ALTER COLUMN DocDay_Id int IDENTITY(1,1) PRIMARY KEY NOT NULL
Create table DoctorDays
(
DocDay_Id int IDENTITY(1,1) NOT NULL,
Doc_Id int FOREIGN KEY REFERENCES Doctor(Doc_Id) NOT NULL,
Day_Id int FOREIGN KEY REFERENCES Dayss(Day_Id) NOT NULL
)
To create a clustered primary key on an existing table:
ALTER TABLE DoctorDays ADD CONSTRAINT PK_DocDays
PRIMARY KEY CLUSTERED (DocDay_Id);
To create a non clustered primary key on an existing table:
ALTER TABLE DoctorDays ADD CONSTRAINT PK_DocDays
PRIMARY KEY NONCLUSTERED (DocDay_Id);
FIDDLE DEMO HERE
See the document in below link:
Alter Statement Documents

Differences between "foreign key" and "constraint foreign key"

I mean for example I can create table like
create table XTable
(
idt int not null primary key,
value nvarchar(50),
idq int,
constraint fk_idq foreign key(idq) references YTable(idq)
)
and I can create it like this
create table XTable
(
idt int not null primary key,
value nvarchar(50),
idq int,
foreign key(idq) references YTable(idq)
)
I usually create table like in the second example but now I'm curious about the first example. What is the difference?
The first one assigns a user-defined name to the foreign key, the second one will assign a system-generated name to the foreign key.
User-defined foreign key names can be useful for subsequent statements like these:
ALTER TABLE XTable DROP CONSTRAINT fk_idq;
ALTER TABLE XTable ENABLE CONSTRAINT fk_idq;
ALTER TABLE XTable DISABLE CONSTRAINT fk_idq;
It's harder to alter constraints with system-generated names, as you have to discover those names first.
The first option is purely for naming the constraint.
From SQL FOREIGN KEY Constraint
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax
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)
)
Also, from CREATE TABLE (Transact-SQL) one can see that [ CONSTRAINT constraint_name ] is optional.
Apart from controlling the name, nothing really. SQL Server will supply a name if you omit it. FYI, you only need this syntax (SQL Fiddle):
create table XTable
(
idt int not null primary key,
value nvarchar(50),
idq int references YTable(idq)
)
Here's a fuller example.

SQL Server 2008 - deleting rows with FK constraints

I've got SQL database in SQL Server 2008 generated as follows:
CREATE TABLE Client (
ID bigint,
Code varchar(50),
ClientID int NOT NULL
);
ALTER TABLE Client
ADD CONSTRAINT PK_Client PRIMARY KEY CLUSTERED (ClientID);
CREATE TABLE Company (
ID bigint,
Description nvarchar(100),
SubsidiaryOf bigint,
companyID int NOT NULL,
FK_Client_Company int,
PK_Company int
);
ALTER TABLE Company
ADD CONSTRAINT PK_Company PRIMARY KEY CLUSTERED (companyID);
ALTER TABLE Company
ADD CONSTRAINT (ID = ID) FOREIGN KEY (FK_Client_Company)
REFERENCES Client (ClientID);
ALTER TABLE Company
ADD CONSTRAINT (SubsidiaryOf = ID) FOREIGN KEY (PK_Company)
REFERENCES Company (companyID);
CREATE TABLE ContactData (
ID bigint,
LocationID bigint,
Contact nvarchar(50),
contactDataID int NOT NULL,
PK_Location int
);
ALTER TABLE ContactData
ADD CONSTRAINT PK_ContactData PRIMARY KEY CLUSTERED (contactDataID);
ALTER TABLE ContactData
ADD CONSTRAINT (LocationID = ID) FOREIGN KEY (PK_Location)
REFERENCES Location (locationID);
CREATE TABLE Location (
ID bigint,
CompanyID bigint,
Country nvarchar(50),
ZIPCode nvarchar(50),
locationID int NOT NULL,
PK_Company int
);
ALTER TABLE Location
ADD CONSTRAINT PK_Location PRIMARY KEY CLUSTERED (locationID);
ALTER TABLE Location
ADD CONSTRAINT (CompanyID = ID) FOREIGN KEY (PK_Company)
REFERENCES Company (companyID);
And would like to delete all the Companies with ID > 140000 (with related rows in other tables). I tried some combination of INNER JOINs all together in one transaction, but there is still a problem with FK_Client_Company constraint. Can anyone help me?
One more thing - I cannot add anything/modify DB structure/constraints. It has to be a query-base-solution.
First delete those companies' clients
delete client where id in (select fk_client_company from company where id > 140000)
After that you should be able to run the delete statement on the company table
delete company where id > 140000
I'm 'fairly' sure that's the answer you're looking for but I'm not a 100% positive only because your naming scheme seems a little odd. I'm making the assumption that company.fk_client_company = client.id.

How to create composite primary key in SQL Server 2008

I want to create tables in SQL Server 2008, but I don't know how to create composite primary key. How can I achieve this?
create table my_table (
column_a integer not null,
column_b integer not null,
column_c varchar(50),
primary key (column_a, column_b)
);
CREATE TABLE UserGroup
(
[User_Id] INT NOT NULL,
[Group_Id] INT NOT NULL
CONSTRAINT PK_UserGroup PRIMARY KEY NONCLUSTERED ([User_Id], [Group_Id])
)
Via Enterprise Manager (SSMS)...
Right Click on the Table you wish to create the composite key on and select Design.
Highlight the columns you wish to form as a composite key
Right Click over those columns and Set Primary Key
To see the SQL you can then right click on the Table > Script Table As > Create To
I know I'm late to this party, but for an existing table, try:
ALTER table TABLE_NAME
ADD CONSTRAINT [name of your PK, e.g. PK_TableName] PRIMARY KEY CLUSTERED (column1, column2, etc.)
For MSSQL Server 2012
CREATE TABLE usrgroup(
usr_id int FOREIGN KEY REFERENCES users(id),
grp_id int FOREIGN KEY REFERENCES groups(id),
PRIMARY KEY (usr_id, grp_id)
)
UPDATE
I should add !
If you want to add foreign / primary keys altering, firstly you should create the keys with constraints or you can not make changes. Like this below:
CREATE TABLE usrgroup(
usr_id int,
grp_id int,
CONSTRAINT FK_usrgroup_usrid FOREIGN KEY (usr_id) REFERENCES users(id),
CONSTRAINT FK_usrgroup_groupid FOREIGN KEY (grp_id) REFERENCES groups(id),
CONSTRAINT PK_usrgroup PRIMARY KEY (usr_id,grp_id)
)
Actually last way is healthier and serial. You can look the FK/PK Constraint names (dbo.dbname > Keys > ..) but if you do not use a constraint, MSSQL auto-creates random FK/PK names. You will need to look at every change (alter table) you need.
I recommend that you set a standard for yourself; the constraint should be defined according to the your standard. You will not have to memorize and you will not have to think too long. In short, you work faster.
First create the database and table, manually adding the columns. In which column to be primary key. You should right click this column and set primary key and set the seed value of the primary key.
To create a composite unique key on table
ALTER TABLE [TableName] ADD UNIQUE ([Column1], [Column2], [column3]);
CREATE TABLE UserGroup
(
[User_Id] INT Foreign Key,
[Group_Id] INT foreign key,
PRIMARY KEY ([User_Id], [Group_Id])
)