Link columns in two tables and trigger to automatically update and insert data - sql

I have done a lot of searching and have not found exactly what I am looking for. Sorry if this is a duplicate question, I did not see one that matched my needs.
I have 2 tables:
students:
ID int autoincrement
RegistrationNumber nvarchar
fullname nvarchar
address nvarchar
stream nvarchar
phone nvarchar
and so on
The other table is results:
ID int autoincrement
RegistrationNumber nvarchar
fullname nvarchar
stream nvarchar
GPA nvarchar
I want to connect these tables so that the results table get values from students table, and any insertion/update in students table automatically updates/inserts data accordingly in results table columns to be connected in both tables are RegistrationNumber, fullname and stream.

You need a trigger (or two) that will modify the table Results after insert or update on the Students table. You can start from here: CREATE TRIGGER.
Beside that, not sure if you can, but my suggestion is to have the table Results like this:
Student_ID int
GPA nvarchar
In this way after each insert you have to insert only the Student_ID and when you update a student you won't need to change Results.
Also you can define Student_ID as a Foreign Key to be sure to keep referential integrity.

Related

SSMS will not let me create a PK FK relationship

First, let me say that I am a newbie and that I have read many other posts with the same problem. I have a table called "AllPeople", and in that table I have an integer column called "Ethnicity", which I want to be a foreign key that points at a record in my "RefEthnicities" table. I keep getting the following message:
Unable to create relationship 'FK_AllPeople_RefEthnicities'.
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_AllPeople_RefEthnicities". The conflict occurred in database "MVC-Cemeteries-Dev", table "dbo.RefEthnicities", column 'ID'.
I set up the relationship in the "AllPeople" table and told it that the primary key is the ID column in the "RefEthnicities" and the foreign key is the "Ethnicity" column in the "AllPeople" table. What am I doing wrong? My RefEthnicities table is new; no data in it.
While in design mode I set the ID field in the "RefEthnicities" table set as primary key by clicking the small box to the left of the name "ID", and down below in this same window in the column properties tab, I told it to set the index specification to "yes".
I am sure it is something simple that I am doing but I can't figure it out.
Error Message
Constraint Folder
Setting Up PK FK Link
As my limited information in the question, there 2 possibilities
NULL or Blank '' value for column Ethnicity in table AllPeople
SELECT A.Ethnicity,A.*
FROM dbo.AllPeople A
WHERE ISNULL(A.Ethnicity,'')=''
Some values column Ethnicity in table AllPeople don't have parent in column ID in table RefEthnicities
SELECT A.Ethnicity,R.ID, *
FROM dbo.AllPeople A
LEFT JOIN RefEthnicities R
ON A.Ethnicity=R.ID
WHERE R.ID IS NULL
If you get any rows in two queries, then you need to fix data in column Ethnicity in table AllPeople.
Read
Ok this still makes no sense. If I create two brand new tables with the following:
table1
ID primary key int not nullable
value varchar
table2FK
table2
ID primary key int not nullable
value varchar
and in table1 I make a relationship between table2FK and Table2.ID, it works perfect with no data saved in the tables. If I use the exact same process in my AllPeople and RefEthnicicties tables, I get the error. This makes no sense. What am I missing?
adam
That fixed it. many thanks. I had a record in my AllPeople table for ethnicity that had a value of 0. Since I didn't have a record in the RefEthnicity Table with an ID of 0, it was telling me that I couldn't do this.
adam

INSERTING a single field into a table, referenced from another table

I need to insert a field in a that references an id field in another table.
The id field it is to going is next to the field 'test' (column - codedescription, table typecategory) and coming from an id field next to the word 'assessment' (column categorydescription, table typecategory)
INSERT INTO codetype
(typecategoryid)
Where codedescription='test'
SELECT id FROM typecategory WHERE categorydescription='Assessment Types'
There are plenty of examples of inserting entire columns but nobody has written how to insert a single field from another table.
table - codetype
id bigserial primary key
codedescription varchar
typecategoryid bigint foreign key to typecatogory on the ID column
Table - typecategory
ID big serial primary key
categorydescription varchar
If the column already exists and there are are already records in the rest of the columns in the table, then you need an UPDATE statement, not an INSERT.
Looks like this post might help you: Update a column of a table with a column of another table in PostgreSQL
maybe
UPDATE codetype c
SET c.typecategoryid = t.id
FROM typecategory t
WHERE c.codedescription = 'test' and t.categorydescription='Assessment Types'

does it worth switching a PRIMARY KEY from the type NVARCHAR to the type INT?

On our SQL SERVER 2008 R2 database we have an COUNTRIES referential table that contains countries. The PRIMARY KEY is a nvarchar column:
create table COUNTRIES(
COUNTRY_ID nvarchar(50) PRIMARY KEY,
... other columns
)
The primary key contains values like 'FR', 'GER', 'US', 'UK', etc. This table contains max. 20 rows.
We also have a SALES table containing sales data:
create table SALES(
ID int PRIMARY KEY
COUNTRY_ID nvarchar(50),
PRODUCT_ID int,
DATE datetime,
UNITS decimal(18,2)
... other columns
)
This sales table contains a column named COUNTRY_ID, also of type nvarchar (not a primary key). This table is much larger, containing around 20 million rows.
Inside our app, when querying on the SALES table, we filter almost every time on the COUNTRY_ID. Even like this it takes too long to perform most of aggregation queries (even with the proper indexes in place)
We're in a development phase to improve the query performance on the SALES table. My question is:
Does it worth switching the COUNTRY_ID type from nvarchar(50) to the type int? If the column COUNTRY_ID is converted in both tables to the type int, can I expect a better performance when joining the two tables?
I would personally recommend changing COUNTRY_ID from nvarchar(50) to an INT. An int uses 4bytes of data and is usually quicker to JOIN than VARCHAR.
You can also check to see if the space used is reduced by using the stored procedure sp_spaceused
EXEC sp_spaceused 'TableName'

SQL Foreign Keys/Relationships

Having briefly studied databases in college, I haven't worked with them since and have drawn a bit of a blank, so I was wondering if someone could help me out. I have a database called Convert, which holds the following tables:
**File**
ID int PK
ISBN nvarchar(MAX)
UserName nvarchar(50)
CoverID
PDFID
**PDF**
PDFID int PK
FileContent image
MimeType nvarchar
FileName nvarchar
**Cover**
CoverID int PK
FileContent image
MimeType nvarchar
FileName nvarchar
I've just drawn a blank on two things really.
Relationships. I think if I a sql query such as below I will create foreign keys:
Alter TABLE Cover ADD FOREIGN KEY (CoverID) REFERENCES File (CoverID)
What I need to do is create one to one relationships --> One File will have one Cover, and one PDF.
The second is thing I'm having difficulty getting my head around again is the insert statements. Any advice on how I should handle those would be appreciated?
I'm using SQL Server 2008 Also.
If you need to retain your current table structure (and #none is right - if it's really a one-to-one relationship there's no benefit to having three tables) you can get what you want by doing the following:
Define two foreign key constraints on File, one on File.PDFID referencing PDF.PDFID and the other on File.CoverID referencing Cover.CoverID.
Define two UNIQUE constraints on the File table, one on File.PDFID and the other on File.CoverID.
Share and enjoy.
if you want to ensure that a relation will have one to one relationship, then make one big table.
one table where you have
create table
ID int PK
ISBN nvarchar(MAX)
UserName nvarchar(50)
PDFFileContent image
PDFFileName nvarchar
CoverFileContent image
CoverFileName nvarchar
what you might ment in your original design is to make one table that could contain all 3 types and each row is different by having different value at "mime type" which is also possible, if hold keys that relet the table to itself.
such as
create table
ID int pk
ISBN nvarchar(max)
userName nvarchar(50)
pdfID int fk table2 id
coverID int fk table 2 id
create table2
id pk int
fileContent image
fileName nvarchar
mimetype (something)
A true one-to-one relationship would look like:
which is essentially a vertically partitioned table. In this case, you may also consider simply putting all columns in one table.

How to move data between multiple database's table while maintaining foreign-key relationships/referential integrity?

I'm trying to figure out the best way to move/merge a couple tables of worth of data from multiple databases into one.
I have a schema similar to the following:
CREATE TABLE Products(
ProductID int IDENTITY(1,1) NOT NULL,
Name varchar(250) NOT NULL,
Description varchar(1000) NOT NULL,
ImageID int NULL
)
CREATE TABLE Images (
ImageID int IDENTITY(1,1) NOT NULL,
ImageData image NOT NULL
)
With a foreign-key of the Products' ImageID to the Images' ImageID.
So what's the best way to move the data contained within these table from multiple source databases into one destination database with the same schema. My primary issue is maintaining the links between the products and their respective images.
In SQL Server, you can enable identity inserts:
SET IDENTITY_INSERT NewTable ON
<insert queries here>
SET IDENTITY_INSERT NewTable OFF
While idenitity insert is enabled, you can insert a value in the identity column like any other column. This allows you to just copy the tables, for example from a linked server:
insert into newdb.dbo.NewTable
select *
from oldserver.olddb.dbo.OldTable
I preposition the data in staging tables (Adding a newid column to each). I add a column temporarily to the table I'm merging to that is Oldid. I insert the data to the parent table putting the currect oldid inthe oldid column. I use the oldid column to join to the staging table to populate the newid column in the staging table. Now I have the New FK ids for the child tables and ccan insert using them. If you have SQL server 2008, you can use the OUTPUT clause to return the old and newids to a temp table and then use from there rather than dding the column. I prefer, to have the change explicitly stored ina staging table though to troubleshoot issues in the conversion. At the end nullout the values inteh oldid column if you are then going to add records from a third database or drop it if you are done. Leave the staging tables in place for about a month, to make research into any questions easier.
In this case you could move the images and then move the products. This would ensure that any image a product has a reference to will already be in place.