Using a Query or Stored Procedure to Report on the differences between two tables - sql

I have created the following two tables:
Table1:
CREATE TABLE employees
(
PersonID NUMBER(10) NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
JobRole varchar(255) NOT NULL,
Location varchar(255) NOT NULL,
CONSTRAINT pk_employee PRIMARY KEY (personid) USING INDEX
);
Table 2:
CREATE TABLE DBAteam
(
PersonID NUMBER(10) NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
JobRole varchar(255) NOT NULL,
Location varchar(255) NOT NULL,
CONSTRAINT pk_dbateam PRIMARY KEY (personid) USING INDEX
);
The following is the trigger and stored procedure I'm using to populate the two tables:
Trigger:
CREATE OR REPLACE TRIGGER trg_trigger_test AFTER INSERT ON employees FOR EACH ROW
BEGIN
p_procedure_test(:NEW.personid, :NEW.lastname, :NEW.firstname, :NEW.jobrole, :NEW.location);
END trg_trigger_test;
/
Stored procedure:
CREATE OR REPLACE PROCEDURE p_procedure_test
(
i_personid IN employees.personid%TYPE,
i_lastname IN employees.lastname%TYPE,
i_firstname IN employees.firstname%TYPE,
i_jobrole IN employees.jobrole%TYPE,
i_location IN employees.location%TYPE
) AS
--
BEGIN
--
INSERT INTO dbateam
(
personid,
lastname,
firstname,
jobrole,
location
)
VALUES
(
i_personid,
i_lastname,
i_firstname,
i_jobrole,
i_location);
--
END p_procedure_test;
/
I need to find a way in which I can create a stored procedure or query to show me the differences between the two tables
Any help would be greatly appreciated, I've been struggling with this.

In Oracle :
SELECT * FROM table1
MINUS
SELECT * FROM table2
OR
SELECT *
FROM table1 t1
WHERE NOT EXISTS( SELECT 1
FROM table2 t2
WHERE t1.some_key = t2.some_key )
In Mysql:
SELECT * FROM table1
WHERE ID NOT IN (SELECT ID FROM table2 )
UNION
SELECT * FROM table2
WHERE ID NOT IN (SELECT ID FROM table1 )
In SQL SERVER
select * from table1
except
select * from table2

Related

I need to JOIN using a linking table

The three tables are as follows:
CREATE TABLE Artist
(
ArtistKey char(20) NOT NULL PRIMARY KEY,
ArtistName varchar(50) NOT NULL
)
CREATE TABLE AlbumInfo
(
AlbumInfoKey char(20) NOT NULL PRIMARY KEY,
AlbumTitle varchar(50) NOT NULL,
AlbumDate date NULL,
AlbumStudio varchar(50) NULL
)
CREATE TABLE AlbumArtist
(
AlbumInfoKey char(20) NOT NULL,
ArtistKey char(20) NOT NULL,
PRIMARY KEY CLUSTERED
(
AlbumInfoKey ASC,
ArtistKey ASC
))
My objective is to list all of the artists and their albums. I can't seem to get anything to work.
I have tried:
SELECT
Artist.ArtistName,
AlbumInfo.AlbumTitle
FROM Artist
JOIN AlbumArtist
ON Artist.ArtistKey = AlbumArtist.ArtistKey
JOIN AlbumInfo
On AlbumInfo.AlbumInfoKey = AlbumArtist.AlbumInfoKey
However this gives me back nothing not even an error.
Alright, I had to re-do your whole task, and I have come up with more professional, and better way of managing database. You need to drop those tables, and re-do whole thing like show in code below :
--First create Artist table
CREATE TABLE Artist
(
Artist_key int PRIMARY KEY IDENTITY(1,1),
ArtistName varchar(50) NOT NULL,
);
--Then create Album table
CREATE TABLE AlbumInfo
(
Album_key int NOT NULL PRIMARY KEY IDENTITY(1,1),
AlbumTitle varchar(50) NOT NULL,
AlbumDate date NULL,
AlbumStudio varchar(50) NULL,
Artist_key int FOREIGN KEY (Artist_key) REFERENCES Artist(Artist_key)
);
-- Must have Artist data before referencing in the album table
INSERT into Artist (ArtistName) values ('John')
INSERT into AlbumInfo (AlbumTitle,AlbumDate,AlbumStudio,Artist_key) values ('ABC3','2020-6-12','Def3',(select Artist_key from Artist where Artist_key = 1 ))
--test if data has been inserted
SELECT * FROM Artist
SELECT * FROM AlbumInfo
-- And finally this query will show the Artist with their relevant Albums
SELECT ArtistName,af.AlbumTitle,AlbumStudio from Artist a join AlbumInfo af on af.Artist_key = a.Artist_key
And the result is :

SQL Query: I want to display UserName and role_discription using a junction table

Hi can someone please help?
I have three tables tblUsers, tblRoles and tblUserRoles
How do I display UserName from a tblUsers table and role_discription
from tblRoles table.
CREATE TABLE tblRoles(
roleID int IDENTITY(1,1) PRIMARY KEY NOT NULL,
role_description varchar(50) NOT NULL
);
)CREATE TABLE tblUsers(
userID int IDENTITY(1,1) PRIMARY KEY,
FirstName varchar(50) NOT NULL,
LastName varchar(50) NOT NULL,
Age int NOT NULL,
UserName varchar(50) NOT NULL,
Password varchar(50) NOT NULL);
create table tblUserRoles (
userID int REFERENCES tblUsers(userID) NOT NULL,
roleID int REFERENCES tblRoles(roleID)NOT NULL,
);
alter table tblUserRoles
Add Constraint PK_UserRoles
Primary Key Clustered (userID,roleID)
I know basic SELECT statements and can show everything in tblUserRoles table but would like to show names and descriptions instead of ID numbers
Here is a query to display user_name and role_description
SELECT t1.UserName , t2.role_description from tblUsers t1 INNER JOIN tblUserRoles t3 ON t1.userID = t3.userID INNER JOIN tblRoles t2 on t3.roleID = t2.roleID
Here the 1st join will join tables tblUsers and tblUserRoles on column userID and the 2nd join will join tables tblUserRoles and tblRoles on column roleID.

Insert into multiple(7) tables with no duplicates

Trying to create a query/SP that will take data from one table and insert it into multiple tables. I have one main table that everything is put into at the beginning like a temp table.
Temp table
CREATE TABLE Employee
(
userID INT IDENTITY(1,1) NOT NULL,
userName VARCHAR(50) NULL,
FirstName VARCHAR(50) NULL,
LastName VARCHAR(50) NUll,
UserPassWd VARCHAR(50) NULL,
EmailId VARCHAR(100) NULL
CONSTRAINT PK_Employee PRIMARY KEY (userID)
)
Than when employee is verified it will be split up into multiple tables that only need a field or two from the temp table as needed. The UserEmail table I have listed below is one of the tables. I'm trying to get it to work for one table right now and then I'm guessing i will just copy the insert part and change the table name and attributes to the new tables
Here is what i have so far.
DECLARE #EMAIL VARCHAR(100)
DECLARE #USERID INT
SELECT #USERID = userID
,#EMAIL = EmailId
FROM Employee
WHERE userID = 1004
INSERT INTO UserEmail
(
EmailAddress
,EmailTypeID
,ExternalUserID
,Active
,CreatedByID
,CreatedDate
,UpdatedByID
,UpdatedDate
)
SELECT #EMAIL -- Email Address
,1 -- Email Type
,1 -- ExternalUserID
,1 -- Active
,1 -- CreatedByID
,CURRENT_TIMESTAMP -- CreatedDate
,1
,CURRENT_TIMESTAMP -- UpdatedDate
FROM Employee X
WHERE 1=1
AND X.userID = '####'-- INSERT USERID HERE for testing
This will insert the record into the UserEmail table but will create duplicate users, which i cant have so I tried adding this but it doesn't do what I want it to do.
WHERE 1=1
AND NOT EXISTS(
SELECT userID
FROM Employee
WHERE userID = 1004
)
Any guidance or help would be much appreciated. Thank You!
If you only like NOT to insert to UserEmail if user already exists just extend
INSERT INTO UserEmail ....
SELECT ....
FROM ....
WHERE ..
AND NOT EXISTS (select 1 from UserEmail where EmailAddress = X.emailAddress)
Otherwise review MERGE syntax (https://learn.microsoft.com/en-us/sql/t-sql/statements/merge-transact-sql)

INSERT Conflict on Virtual Table SQL

I am having a problem on the INSERT because of a FK reference. The process goes like this:
I create the table Cuentas, and Cuentas_Con_RowNumber
I select from a huge table with over 3 million records. Because some are repeated and I need to store only 1 "cuenta", I made the tempDB. I have to do this, because on the huge db there are many records with the same Cuenta_Nro with different transactions, and I just need one.
I select from the tempDB all the columns but the RowNumber and then insert it into the Cuentas table.
The problem is that the tempDB Pais (country) column is not a FK which references to the Paises (countries) table, and on the original table (Cuentas) it does, therefore, it crashes.
Code:
CREATE TABLE Paises
(
Pais_Id numeric(18,0) PRIMARY KEY NOT NULL,
Pais_Nombre varchar(255) NOT NULL
)
CREATE TABLE Cuentas
(
Cuenta_Nro numeric(18,0) PRIMARY KEY NOT NULL,
Cuenta_Estado varchar(255),
Cuenta_Moneda varchar(255) DEFAULT 'Dolar',
Cuenta_Tipo numeric(18,0)
FOREIGN KEY REFERENCES Tipo_De_Cuentas(Tipo_De_Cuenta_Id),
Cuenta_PaisOrigen numeric(18, 0)
FOREIGN KEY REFERENCES Paises(Pais_Id),
Cuenta_PaisAsignado numeric(18, 0)
FOREIGN KEY REFERENCES Paises(Pais_Id),
Cuenta_Fec_Cre datetime,
Cuenta_Fec_Cierre datetime,
Cuenta_Tarjeta numeric(18, 0)
FOREIGN KEY REFERENCES Tarjetas(Tarjeta_Nro),
Cuenta_Cliente numeric(18, 0)
FOREIGN KEY REFERENCES Clientes(Cliente_Id)
)
CREATE TABLE #Cuentas_Con_RowNumer
(
Cuenta_Nro numeric(18,0) PRIMARY KEY NOT NULL,
Cuenta_Estado varchar(255),
Cuenta_PaisOrigen numeric(18,0)),
Cuenta_Fec_Cre datetime,
Cuenta_Fec_Cierre datetime,
Cuenta_Cliente numeric(18,0),
Cuenta_Tarjeta numeric(18,0),
RowNumber int
)
INSERT INTO #Cuentas_Con_RowNumer
SELECT *
FROM (SELECT
Maestro.Cuenta_Numero, Maestro.Cuenta_Estado, Maestro.Cuenta_Pais_Codigo,
Maestro.Cuenta_Fecha_Creacion, Maestro.Cuenta_Fecha_Cierre, Clientes.Cliente_Id, Maestro.Tarjeta_Numero,
ROW_NUMBER() OVER (PARTITION BY Maestro.Cuenta_Numero ORDER BY Maestro.Cuenta_Numero) AS RowNumber
FROM gd_esquema.Maestra Maestro, dbo.Clientes
WHERE
Clientes.Cliente_Apellido = Maestro.Cli_Apellido AND
Clientes.Cliente_Nombre = Maestro.Cli_Nombre) AS a
WHERE a.RowNumber = '1'
INSERT INTO Cuentas
(
Cuenta_Nro, Cuenta_Estado, Cuenta_PaisOrigen, Cuenta_Fec_Cre,
Cuenta_Fec_Cierre, Cuenta_Cliente, Cuenta_Tarjeta
)
SELECT
Cuenta_Nro, Cuenta_Estado, Cuenta_PaisOrigen, Cuenta_Fec_Cre,
Cuenta_Fec_Cierre, Cuenta_Cliente, Cuenta_Tarjeta
FROM #Cuentas_Con_RowNumer
The error message is:
Instrucción INSERT en conflicto con la restricción FOREIGN KEY "FK__Cuentas__Cuenta___24B338F0". El conflicto ha aparecido en la base de datos "GD1C2015", tabla "dbo.Paises", column 'Pais_Id'.
The issue is because Maestro.Cuenta_Pais_Codigo column is being pulled from gd_esquema.Maestra table which in turn is going as Cuenta_PaisOrigen in target table and has a foreign key defined.
There will be some records which are being selected for insert Cuentas table that doesn't have a matching Pais_Id record in dbo.Paises table.
You can add a inner join as below and check the results as :
INSERT INTO #Cuentas_Con_RowNumer
SELECT *
FROM (SELECT
...
FROM gd_esquema.Maestra Maestro
inner join dbo.Clientes on
Clientes.Cliente_Apellido = Maestro.Cli_Apellido AND
Clientes.Cliente_Nombre = Maestro.Cli_Nombre
inner join Paises P on Maestro.Cuenta_Pais_Codigo = P.Pais_Id
) AS a
WHERE a.RowNumber = '1'

How to group several INSERTs?

I'm inserting data from one table into several others. The first insert will create a new userid. This new userid will be used in succeeding inserts. I will also continue inserting username from the source table into other tables. The chain of inserts below are for one user. There will be probably 2000 users involved.
I'm familiar with how this can be done using a cursor. Is there some other way to do this chain of inserts without a cursor?
insert into table 1 using #username and #firstname from source table
insert into table 2 using userid generated from table 1 (userid1)
insert into table 3 using #username and userid1
insert into table 4 using userid1
You can use the Output Clause of an Insert statement to capture generated Ids in bulk.
For example:
Create Table dbo.Source (
FirstName nvarchar(100),
LastName nvarchar(100)
);
Create Table dbo.Attrs (
Id int Identity Not Null Primary Key,
Name nvarchar(100) Not Null,
DefaultVal nvarchar(100)
);
Create Table dbo.Table1 (
Id Int Identity Not Null Primary Key,
FirstName nvarchar(100),
LastName nvarchar(100)
);
Create Table dbo.Table2 (
Id int Identity Not Null Primary Key,
Table1ID int Not Null Foreign Key References dbo.Table1 (Id),
AttrId int Not Null Foreign Key References dbo.Attrs (Id)
);
Insert Into dbo.Source Values
(N'Mickey', N'Mouse'),
(N'Donald', N'Duck'),
(N'Goofy', Null);
Insert Into dbo.Attrs Values
('Size', 'Small'),
('Wings', 'No');
Declare #Temp1 Table (Id Int, FirstName nvarchar(100), LastName nvarchar(100))
Declare #Temp2 Table (Id int, Table1ID int, AttrId int)
Insert Into dbo.Table1
(FirstName, LastName)
Output
inserted.Id, inserted.FirstName, inserted.LastName
Into
#Temp1
Select
FirstName, LastName
From
dbo.Source
Insert Into dbo.Table2
(Table1ID, AttrId)
Output
inserted.Id, Inserted.Table1ID, Inserted.AttrID
Into
#Temp2
Select
t.Id,
a.Id
From
#Temp1 t
Cross Join
dbo.Attrs a
Select * From #Temp2
http://sqlfiddle.com/#!3/31110/3