What is the mistake in this SQL statement? - SQL - 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';

Related

ALTER TABLE statement conflicted with the FOREIGN KEY constraint

When creating the foreign key I came across this error. Below is my code.
create table tblPerson(
ID int not null primary key,
Fullname varchar(50) not null,
Email varchar(50) not null,
GenderId int
)
create table tblGender (
ID int not null primary key,
Gender varchar(50) not null
)
alter table tblPerson add constraint tblPerson_GenderId_FK
foreign key (GenderId) references tblGender(ID)
You want to identify any "do not align" rows....
I have made the below.
You won't be able to add the FK constraint, if any rows come back from the SELECT query.
I have also removed the hungarian notation for "tbl". I would advise against it.
create table dbo.Person(
ID int not null primary key,
Fullname varchar(50) not null,
Email varchar(50) not null,
GenderId int )
create table dbo.Gender (
ID int not null primary key,
Gender varchar(50) not null
)
/* any rows below? your FK creation will fail */
Select *, p.GenderId as 'HoustonWeHaveAProblemValue' from dbo.Person p Where Not Exists (Select 1 from dbo.Gender g where g.ID = p.GenderId)
alter table dbo.Person add constraint Person_GenderId_FK
foreign key (GenderId) references dbo.Gender(ID)
Hi please use the following code to achieve your goal :
1-First create tblGender:
create table tblGender (
ID int not null primary key,
Gender varchar(50) not null
)
2-Then create table tblPerson with the relationship between 2 tables since the beginning:
create table tblPerson(
ID int not null primary key,
Fullname varchar(50) not null,
Email varchar(50) not null,
GenderId int references tblGender(ID)
)
works fine.

Get Max record from query SQL Server

I have the following tables
CREATE TABLE Staff
(
staffID int,
fullName varchar(100) NOT NULL,
s_category varchar(25),
s_email varchar(50),
s_contactNo int,
speciality varchar(100),
qualifications varchar(250),
pre_employment varchar(200),
salary numeric(8,2),
staff_gender char(1),
staff_joined_date datetime,
branch_allocated int,
CONSTRAINT PK_Staff
PRIMARY KEY (staffID),
CONSTRAINT FK_Staff_Branch
FOREIGN KEY (branch_allocated) REFERENCES Branch(branchID)
ON DELETE CASCADE,
CONSTRAINT CHK_StaffGender CHECK (staff_gender='M' OR staff_gender='F'),
CONSTRAINT CHK_FullName CHECK (fullName NOT LIKE '%[^A-Za-z ]%'),
CONSTRAINT CHK_SALARY CHECK (salary>0 AND salary<=150000)
);
CREATE TABLE Appointment
(
appID int,
patientId int,
staffId int,
appDateTime DateTime,
CONSTRAINT PK_Appointment PRIMARY KEY (appID),
CONSTRAINT FK_Appointment_Patient
FOREIGN KEY (patientId) REFERENCES Patient(patientID)
ON DELETE CASCADE,
CONSTRAINT FK_Appointment_Staff
FOREIGN KEY (staffId) REFERENCES Staff(staffID)
ON DELETE CASCADE,
CONSTRAINT CHK_AppointmentDate CHECK (appDateTime>=GETDATE())
);
I want to get the doctor(s) with maximum number of patients.
I have created the query as follows.
SELECT
s.staffID AS 'ID',s.fullName AS 'Name', COUNT(a.appID) AS 'Number of Patients'
FROM
Staff s
INNER JOIN
Appointment a ON s.staffID = a.staffId
GROUP BY
s.staffID, s.fullName
ORDER BY
'Number of Patients' DESC
But this returns all doctors. Can you help me to find the doctor with the largest number of patients?
WITH cte AS (
SELECT
s.staffID AS ID,
s.fullName AS Name,
COUNT(a.appID) AS [Number of Patients],
DENSE_RANK() OVER (ORDER BY COUNT(a.appID) DESC) AS rank
FROM Staff s
LEFT JOIN Appointment a
ON s.staffID = a.staffId
GROUP BY s.staffID, s.fullName
)
SELECT
ID, Name, [Number of Patients]
FROM cte
WHERE rank = 1;
Can you try this
SELECT TOP number|percent column_name(s)
FROM table_name
WHERE condition;
on your situation SELECT TOP 1

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 add values of primary key column into foreign key column of other table

How to add values of primary key column into foreign key column of other table: I'm using SQL Server 2012
CREATE TABLE CUSTOMERS( ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL,
ADDRESS CHAR (25) , SALARY DECIMAL (18, 2), PRIMARY KEY (ID));
CREATE TABLE ORDERS ( ID INT NOT NULL, DATE DATETIME, CUSTOMER_ID INT references
CUSTOMERS(ID), AMOUNT VARCHAR (255), PRIMARY KEY (ID));
Here i need to take all values from primary key table 'customers' from column 'ID' to foreign key table orders to column 'ID'
DECLARE #A INT, #DATE DATETIME, #C_ID INT, #AMOUNTS INT;
SET #A =1;
SET #DATE ='2009-10-08 00:00:00';
SET #C_ID = 100
SET #AMOUNTS=1000;
WHILE #A <= 7
BEGIN
SET #DATE = DATEADD(DAY,1,#DATE);
SET #C_ID = #C_ID + 1
SET #AMOUNTS = #AMOUNTS+100;
INSERT INTO ORDERS(ID, DATE, CUSTOMER_ID,AMOUNT)
SELECT ID, #DATE, #C_ID, #AMOUNTS FROM CUSTOMERS WHERE AGE like'%';
SET #A = #A+1;
END
You have set your Orders table up with a Foreign Key on Customer_ID that references Customers(ID). So you can you only add rows to Orders if the ID exists in Customers. Right now you are trying to insert 101-107 in that column every time, so check if those IDs exists in Customers.
It seems to me that you SHOULD want to insert the Customers.ID column in Orders.Customer_ID, rather than Orders.ID. Is that what you meant?

Sql query join and aggragation at the same time

How can I Select the Sum of the ProjectPossibilityRatio column from the ProjectCompletion table given the ProjectID? I couldnt find sum:
SELECT pp.ProjectID,
pp.ProjectAlias,
Sum(pd.projectpossibilityratio)
FROM project pp
INNER JOIN projectcompletion pc
ON pp.projectId = pc.projectID
JOIN projectprocedure pd
ON pd.projectprocedureID = pc.projectprocedureID
GROUP BY pd.projectpossibilityratio
Here are the table definitions:
Create TABLE ProjectType(
ProjectTypeID int identity(1,1),
ProjectTypeName nvarchar(100),
Description nvarchar(200),
primary key(ProjectTypeID)
)
CREATE TABLE Project(
ProjectID int identity(1,1),
ProjectAlias nvarchar(100),
ProjectTypeID int foreign key references ProjectType(ProjectTypeID),
MandatedCompanyID int foreign key references Company(CompanyID),
Iscurrent bit,
BuySide bit,
TeamID int foreign key references WorkTeam(TeamID),
ProjectTurnOver varchar(100),
ProjectStartDate Datetime
primary key(ProjectID))
CREATE TABLE ProjectProcedure(
ProjectProcedureID int identity(1,1),
ProjectProcedureName nvarchar(100),
ProjectProcedureDescription nvarchar(200),
ProjectType int foreign key references ProjectType(ProjectTypeID),
ProjectProcedurePosition int,
ProjectProcedureTime smallint,
ProjectPossibilityRatio int,
Primary Key(ProjectProcedureID))
CREATE TABLE ProjectCompletion(
ProjectID int foreign key references Project(ProjectID),
ProjectProcedureID int foreign key references ProjectProcedure(ProjectProcedureID),
StartDate Datetime,
IsCompletedDate Datetime
Primary Key(ProjectID,ProjectProcedureID)
)
Add all the column names that you are selecting to the group by list.
Try this:
SELECT pp.ProjectID,pp.ProjectAlias,Sum(pd.projectpossibilityratio)
FROM project pp INNER JOIN projectcompletion pc ON pp.projectId=pc.projectID
JOIN projectprocedure pd ON pd.projectprocedureID=pc.projectprocedureID
GROUP BY pp.ProjectID,pp.ProjectAlias
And I agree with LeftyX, you should go back and accept answers