INSERT Conflict on Virtual Table SQL - 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'

Related

What is the mistake in this SQL statement? - SQL

SQL query:
insert into Transaction_Details (Trans_Date, Trans_Type)
values (GetDate(), 'WITHDRWAL')
from Transaction_Details t
inner join Acc_Details a on t.UserID = a.UderId
where a.Card_No = '1234567890123456';
Transaction table columns:
Trans_ID int PRIMARY KEY IDENTITY(1,1),
Trans_Date datetime,
Trans_Type varchar(20),
UserID int foreign key references User_Details(UserID)
Card_Id varchar(16) foreign key references User_Card_Details,
Acc_No int foreign key references Acc_Details(Acc_No)
Acc_Details columns:
Acc_Id int,
Acc_No int PRIMARY KEY,
Card_No varchar(16) foreign key references User_Card_Details(Card_No),
UserId int foreign key references User_Details(UserID),
Balance int,
BankName varchar(15)
I get this error:
Incorrect syntax near the keyword 'from'
To insert based on a select it's this:
insert into Transaction_Details (Trans_Date, Trans_Type)
select GetDate(),
'WITHDRWAL'
from Transaction_Details t
inner join Acc_Details a on t.UserID = a.UderId
where a.Card_No = '1234567890123456';

How to combine two selects with same value but not the same INNER JOIN

I have to need a project school, a site like ebay
with bid.
I have to make a select who select
the name of the seller
the name of the last "customer" (bid)
BUT THE PROBLEM is that there two value was in the same table, so for access to the value I need to make 2 select with different INNER JOIN (look the diag for understand)
I have made two selects but I don't understand how to make a single select.
SELECT nom AS nameSeller
FROM ENCHERES e
INNER JOIN ARTICLES_VENDUS ac ON ac.no_article = e.no_article
INNER JOIN UTILISATEURS u ON u.no_utilisateur = ac.no_utilisateur
WHERE nom_article LIKE '%ta%'
SELECT nom AS nameCustomer
FROM ENCHERES e
INNER JOIN UTILISATEURS u ON e.no_utilisateur = u.no_utilisateur
WHERE e.no_utilisateur= 57
what i have with two select
First select
nameCustomer
john
Second select
nameSeller
bryan
What i want in one select
nameSeller
nameCustomer
bryan
john
Fil to the script to create table and bdd
-- Script de création de la base de données ENCHERES
-- type : SQL Server 2012
--
CREATE DATABASE BDDTEST2
GO
USE BDDTEST2
GO
CREATE TABLE CATEGORIES (
no_categorie INTEGER IDENTITY(1,1) NOT NULL,
libelle VARCHAR(30) NOT NULL
)
ALTER TABLE CATEGORIES ADD constraint categorie_pk PRIMARY KEY (no_categorie)
CREATE TABLE ENCHERES (
no_utilisateur INTEGER NOT NULL,
no_article INTEGER NOT NULL,
date_enchere datetime NOT NULL,
montant_enchere INTEGER NOT NULL
)
ALTER TABLE ENCHERES ADD constraint enchere_pk PRIMARY KEY (no_utilisateur, no_article)
CREATE TABLE RETRAITS (
no_article INTEGER NOT NULL,
rue VARCHAR(30) NOT NULL,
code_postal VARCHAR(15) NOT NULL,
ville VARCHAR(30) NOT NULL
)
ALTER TABLE RETRAITS ADD constraint retrait_pk PRIMARY KEY (no_article)
CREATE TABLE UTILISATEURS (
no_utilisateur INTEGER IDENTITY(1,1) NOT NULL,
pseudo VARCHAR(30) NOT NULL,
nom VARCHAR(30) NOT NULL,
prenom VARCHAR(30) NOT NULL,
email VARCHAR(20) NOT NULL,
telephone VARCHAR(15),
rue VARCHAR(30) NOT NULL,
code_postal VARCHAR(10) NOT NULL,
ville VARCHAR(30) NOT NULL,
mot_de_passe VARCHAR(30) NOT NULL,
credit INTEGER NOT NULL,
administrateur bit NOT NULL
)
ALTER TABLE UTILISATEURS ADD constraint utilisateur_pk PRIMARY KEY (no_utilisateur)
CREATE TABLE ARTICLES_VENDUS (
no_article INTEGER IDENTITY(1,1) NOT NULL,
nom_article VARCHAR(30) NOT NULL,
description VARCHAR(300) NOT NULL,
date_debut_encheres DATE NOT NULL,
date_fin_encheres DATE NOT NULL,
prix_initial INTEGER,
prix_vente INTEGER,
no_utilisateur INTEGER NOT NULL,
no_categorie INTEGER NOT NULL
)
ALTER TABLE ARTICLES_VENDUS ADD constraint articles_vendus_pk PRIMARY KEY (no_article)
ALTER TABLE ARTICLES_VENDUS
ADD CONSTRAINT encheres_utilisateur_fk FOREIGN KEY ( no_utilisateur )
REFERENCES UTILISATEURS ( no_utilisateur )
ON DELETE NO ACTION
ON UPDATE no action
ALTER TABLE ENCHERES
ADD CONSTRAINT encheres_articles_vendus_fk FOREIGN KEY ( no_article )
REFERENCES ARTICLES_VENDUS ( no_article )
ON DELETE NO ACTION
ON UPDATE no action
ALTER TABLE RETRAITS
ADD CONSTRAINT retraits_articles_vendus_fk FOREIGN KEY ( no_article )
REFERENCES ARTICLES_VENDUS ( no_article )
ON DELETE NO ACTION
ON UPDATE no action
ALTER TABLE ARTICLES_VENDUS
ADD CONSTRAINT articles_vendus_categories_fk FOREIGN KEY ( no_categorie )
REFERENCES CATEGORIES ( no_categorie )
ON DELETE NO ACTION
ON UPDATE no action
ALTER TABLE ARTICLES_VENDUS
ADD CONSTRAINT ventes_utilisateur_fk FOREIGN KEY ( no_utilisateur )
REFERENCES UTILISATEURS ( no_utilisateur )
ON DELETE NO ACTION
ON UPDATE no action
Link to insert value
USE BDDTEST2
GO
INSERT INTO [dbo].[UTILISATEURS]
([pseudo]
,[nom]
,[prenom]
,[email]
,[telephone]
,[rue]
,[code_postal]
,[ville]
,[mot_de_passe]
,[credit]
,[administrateur])
VALUES
('zorg'
,'john'
,'john'
,'j#k.c'
,'15454'
,'hjh'
,'hkk'
,'hjgjh'
,'hjkjg'
,0
,0 )
GO
INSERT INTO [dbo].[UTILISATEURS]
([pseudo]
,[nom]
,[prenom]
,[email]
,[telephone]
,[rue]
,[code_postal]
,[ville]
,[mot_de_passe]
,[credit]
,[administrateur])
VALUES
('zorg'
,'bryan'
,'bryan'
,'j#k.c'
,'15454'
,'hjh'
,'hkk'
,'hjgjh'
,'hjkjg'
,0
,0 )
GO
INSERT INTO [dbo].[CATEGORIES]
([libelle])
VALUES
('enfant')
GO
INSERT INTO [dbo].[ARTICLES_VENDUS]
([nom_article]
,[description]
,[date_debut_encheres]
,[date_fin_encheres]
,[prix_initial]
,[prix_vente]
,[no_utilisateur]
,[no_categorie])
VALUES
('Jouet',
'desc',
'2002-01-01',
'2003-01-01',
0,
0,
2,
1)
GO
INSERT INTO [dbo].[ENCHERES]
([no_utilisateur]
,[no_article]
,[date_enchere]
,[montant_enchere])
VALUES
(1,
1,
'2002-02-02',
50)
GO
Thanks
You can use a CROSS APPLY to pull back the buyer for each of the sellers. Consider the following:
SELECT u.nom AS nameSeller, x.nom nameBuyer
FROM ENCHERES e
INNER JOIN ARTICLES_VENDUS ac ON ac.no_article = e.no_article
INNER JOIN UTILISATEURS u ON u.no_utilisateur = ac.no_utilisateur
CROSS APPLY(
select u.nom
from UTILISATEURS u WHERE u.no_utilisateur = e.no_utilisateur
) X
lead will move the current row to 1 place above
Union will join data in single column
you need to have a common factor like date for order by clause
https://www.mssqltips.com/sqlservertutorial/9127/sql-server-window-functions-lead-and-lag/
with main_data as (
SELECT nom AS nameSeller,
'Seller' as category_seller_or_customer
FROM ENCHERES e
INNER JOIN ARTICLES_VENDUS ac ON ac.no_article = e.no_article
INNER JOIN UTILISATEURS u ON u.no_utilisateur = ac.no_utilisateur
WHERE nom_article LIKE '%ta%'
union
SELECT nom AS nameCustomer,
'Customer' as category_seller_or_customer
FROM ENCHERES e
INNER JOIN UTILISATEURS u ON e.no_utilisateur = u.no_utilisateur
WHERE e.no_utilisateur= 57
),
getting_seller_and_buyer AS (
select
*,
lead(category_seller_or_customer)
over(order by
[some date factor or something that both have in common]
) as current_seller_or_customer
from main_data
)
select
*,
case
when category = 'Seller' then current_seller_or_customer else end as seller,
case
when category = 'Customer' then current_seller_or_customer else end as customer
from
getting_seller_and_buyer

How to join in sql with multiple tables (need) join multiple references?

Some table only have identity columns but this is because this is a example only.
create table producto(
idproducto int identity primary key
)
create table inventario(
idInventario id int identity primary key,
idproducto int,
foreign key (idproducto) references producto(idproducto)
)
create table sucursal(
idSucursal id int identity primary key
)
create table inventariosucursal(
idinventariosucursal id int primary key,
idsucursal int,
idinventario int,
foreign key (idsucursal) references sucursal (idsucursal),
foreign key (idinventario) references inventario (idinventario),
)
create table mejoresventasxsucursal
(
mejoresventasxsucursal id int primary key,
idsucursal int,
idproducto int,
foreign key (idsucursal) references sucursal(idsucursal),
foreign key (idproducto) references producto (idproducto)
)
What do I need?
select the stocking ( inventario table ) by every branch office (sucursal table) but only most selled products (mejoresventasxsucursal table).
the problem is mejoresventasxsucursal table does "join" with 2 tables product and sucursal but after i have other table with does "join" with same 2 tables product and sucursal.
select s.id,i.id,p.id,
from producto p
join inventario i on p.idproducto = i.idproducto
join inventariosucursal i_s on i_s.idinventario = i.idinventario
join sucursal s on i_s on i_s.idsucursal = s.idsucursal
join producto p on i.producto = p.idproducto
join mejoresventasxsucursal mv on mv.idsucursal = s.idsucursal
Here is the problem. I need join mejoresventasxsucursal with producto. I know I could do something as join producto p2 but I would like to know what is the best way for join with producto. I know other solution is in where condition doing where p.idproducto=mv.idprocucto

SQL How to convert this to a SubQuery?

Learning, be kind.
I am trying to understand how this works and I have done several successful conversions, but this one I am stumped on.
How do I take this code and convert it to a subquery? I'm a little lost.
SELECT o.FirstName + ' ' + o.LastName AS Driver, COUNT(DISTINCT s.vehicleID) NoOfBusesUsed
FROM Operators AS o, Runs AS r, Schedules AS s JOIN Trips AS t
ON s.scheduleID = t.scheduleID
WHERE r.BidDate BETWEEN '09/01/2004' AND '09/30/2004'
GROUP BY o.FirstName + ' ' + o.LastName
HAVING COUNT(s.vehicleID) > 1
Here is how my tables are setup. If more info is needed, I can post.
CREATE TABLE Operators
(
SeniorityNumber char(4) NOT NULL
CONSTRAINT ck_Operators_Seniority
CHECK (SeniorityNumber LIKE '[0-9][0-9][0-9][0-9]'),
FirstName varchar(25) NOT NULL,
LastName varchar(35) NOT NULL,
HireDate smalldatetime
CONSTRAINT ck_Operators_HireDate CHECK (HireDate <=Getdate())
)
CREATE TABLE Trips
(
RouteNumber varchar(4) NOT NULL,
StartLocation varchar(50) NOT NULL,
StartTime time NOT NULL,
EndLocation varchar(50) NOT NULL,
EndTime time NOT NULL,
EffectiveDate smalldatetime NOT NULL
CHECK (EffectiveDate >= cast('1/1/2000' as smalldatetime)),
CONSTRAINT ck_Trips_StartEnd CHECK (EndTime > StartTime)
)
CREATE TABLE Vehicles
(
Manufacturer varchar(50)
DEFAULT 'Gillig',
Model varchar(50),
ModelYear int
DEFAULT DatePart(yyyy,GetDate())
CHECK (ModelYear <= DatePart(yyyy,GetDate())),
PurchaseDate smalldatetime
)
GO
ALTER TABLE operators
ADD OperatorID int IDENTITY --Primary Key
GO
ALTER TABLE Operators
ADD CONSTRAINT pkOperators Primary key (OperatorID)
ALTER TABLE Vehicles
ADD VehicleID int IDENTITY Primary Key
ALTER TABLE Trips
ADD TripID int IDENTITY Primary key
GO
CREATE TABLE Runs
(
RunID int IDENTITY NOT NULL Primary Key,
OperatorID int NOT NULL REFERENCES Operators,
BidDate date NOT NULL
CONSTRAINT ckRunBidDate CHECK
(biddate <= dateadd(mm,6,getdate())) --getdate() + 180
)
GO
CREATE TABLE Schedules
(
ScheduleID int IDENTITY Primary Key,
RunID int NOT NULL,
VehicleID int NOT NULL,
CONSTRAINT fk_Schedules_Runs FOREIGN KEY (RunID)
REFERENCES Runs(RunID),
CONSTRAINT fk_Schedules_Vehicles FOREIGN KEY (VehicleID)
REFERENCES Vehicles
)
ALTER TABLE Trips
ADD ScheduleID int NULL REFERENCES Schedules
When you want to use a query as a sub-query you can use WITH statement or a derived table like:
With:
;WITH subQuery AS (
/* Your query here */
)
SELECT *
FROM subQuery
Derived table
SELECT *
FROM (
/* your query here */
) As subQuery
I think you should use a query like this:
SELECT
o.FirstName + ' ' + o.LastName AS Driver,
DT.cnt AS NoOfBusesUsed
FROM
Operators AS o
JOIN
(SELECT
r.OperatorID,
COUNT(DISTINCT s.VehicleID) AS cnt
FROM
Schedules s
JOIN
Runs r ON s.RunID = r.RunID
) AS DT
ON DT.OperatorID = o.OperatorID
WHERE
ISNULL(DT.cnt, 0) > 1

SQL Query Error: Invalid Column Name

I am new to SQL and I have this problem, I can't seem to search on google.
This is my school work so please be patient with my coding.
Now the problem is i am doing a select query and SQL does not seem to recognize the column I need
here is an attached picture, it just says invalid column but it is clear that the column exist
Dropbox link to the picture
here is the complete code
create database Hairsalon
use Hairsalon
create table Employee
(
Employee_ID int primary key,
Name varchar(20),
Birthday date,
Gender char(1)
);
create table Inventory
(
Inventory_ID int primary key,
Name varchar(30),
Stock int
)
create table Record
(
Transaction_Number int primary key,
Transaction_Date date,
Transaction_Time time
);
alter table Record
drop column Transaction_Date
alter table Record
drop column Transaction_Time
alter table Record
add Transaction_DT varchar(30)
alter table Record
add Transaction_Description varchar(255)
Create table Inventory_Record
(
Transaction_Number int primary key foreign key references Record(Transaction_Number),
Inventory_ID int foreign key references Inventory(Inventory_ID),
);
create table Customer_Record
(
Transaction_Number int foreign key references Record(Transaction_Number),
Customer_ID int primary key,
Service_Description varchar(255),
Pay money
);
create table Customer
(
Customer_ID int foreign key references Customer_Record(Customer_ID),
Name varchar(20),
Payable money,
Session_DT varchar(20)
);
create table Employee_Record
(
Transaction_Number int primary key foreign key references Record(Transaction_Number),
Employee_ID int foreign key references Employee(Employee_ID),
Time_In time,
Time_Out time,
Record_Date date,
Customer_Count int
);
create table Salon
(
Customer_ID int foreign key references Customer_Record(Customer_ID),
Employee_ID int foreign key references Employee(Employee_ID),
Inventory_ID int foreign key references Inventory(Inventory_ID),
Transaction_Number int foreign key references Record(Transaction_Number)
);
alter table Customer
add Session_DT varchar(20)
alter table Customer
drop column Customer_ID
alter table Customer
add Customer_ID int foreign key references Customer_Record(Customer_ID)
alter table Customer_Record
add Employee_ID int foreign key references Employee(Employee_ID)
alter table Employee
add [Type] varchar(15)
alter table Employee
drop column Birthday
alter table Employee
drop column Birthday
alter table Employee_Record
drop column Time_In
alter table Employee_Record
drop column Time_Out
alter table Employee_Record
drop column Record_Date
alter table Employee_Record
add Time_In varchar(20)
alter table Employee_Record
add Time_Out varchar(20)
alter table Employee_Record
add Record_Date varchar(20)
alter table Employee_Record
drop column Customer_Count
insert into Employee
values(1,'Test Employee','M','Cashier','bday')
insert into Employee
values(-1,'Null','N','Null','Null')
insert into Employee values(1,'test1','M','HairDresser','9/8/2014')
INSERT INTO Record values(2,'')
INSERT INTO Customer_Record values(1,1,'asd',123.00,null)
INSERT INTO Customer values(1,'test1',0,'9/8/2014 8:16 AM')
SELECT * FROM Record
select * from Customer
SELECT * FROM Customer_Record
SELECT * FROM Employee
SELECT DISTINCT Customer.Name as 'Customer Name', Employee.Name as 'Attendee'
FROM Customer, Customer_Record, Employee_Record, Employee
WHERE ( Customer_Record.Transaction_Number = Employee_Record.Transaction_Number
AND Employee_Record.Employee_ID = Employee.Employee_ID
AND Customer.Customer_ID = Customer_Record.Customer_ID
) OR ( Customer_Record.Transaction_Number = Employee_Record.Transaction_Number
AND Customer_Record.Employee_ID = -1
AND Customer.Customer_ID = Customer_Record.Customer_ID
)
insert into Employee_Record values(9,1,'10:00','10:99','date')
select * from Record
select * from Customer
select * from Employee
select * from Employee_Record
select * from Customer_Record
select count(Customer_ID) from Customer
select count(Transaction_Number) from Record
insert into Customer
values(1,'test',120,DATEFROMPARTS(32,12,31))
INSERT INTO Customer_Record values(1,1,'Long Haired Customer: ',0, null)
DELETE FROM Customer WHERE Customer_ID = 1
DELETE FROM Customer
DELETE FROM Customer_Record
DELETE FROM Record
DELETE FROM Employee
DELETE FROM Employee_Record
DELETE FROM Inventory
DELETE FROM Inventory_Record
commit
According to the DDL you have presented, it seems quite obvious that Customer_Record has no Employee_ID.
You may have mixed up Customer_Record with Employee_Record or Employee_ID with Customer_ID, but something is wrong.
EDIT I had missed that you alter the table in your script to add the missing columns. In that case, Intellisense (the auto-completion system) does not take it into account unless you manually reload it (using Ctrl + Shift + R). Your query is correct and the errors will disappear once Intellisense is up to date.