Need to read from the employee table and insert into Location table only 1 row if column is having duplicate value
Eg:Employee table
ABC ,1234 , Pavithra p
ABC , 4567, Madhu
BCD ,8910 ,Pavithra Shiva
BCD ,111213, Chaitra
ABCEF , 124567,Priya
Excepted output: Location table
ABC ,1234 , Pavithra p
BCD ,8910 ,Pavithra Shiva
ABCEF , 124567,Priya
How to add this condition in an existing query
merge into Location as loc using (select e.Id, e.No, ln.Name from Employee e
inner join Locationname as ln on e.locationcode=ln.LocationId and
e.emploc=ln.LocId where e.Id is not null ) as emp on loc.id=emp.id
when not matched then
INSERT (Id,No,Name) values(emp.id, emp.no, emp.name);
Naimish MakwanaPosted Dec 19, 2023, 5:27 PM
You can try below query.
Thanks
Naimish
Jayraj ChhayaPosted Dec 19, 2023, 12:00 PM
To add the condition for inserting rows into the Location table only if they don't already exist, you can modify the existing query using the MERGE statement. The MERGE statement allows you to perform insert, update, and delete operations in a single statement based on a specified condition.
Here's the modified query:
In this modified query, the
WHERE NOT EXISTScondition is added to the INSERT statement. This condition checks if a row with the same Id already exists in the Location table. If it does, the row will not be inserted.By adding this condition, the query will only insert rows into the Location table if they don't already exist, based on the Id column.
The expected output in the Location table, as provided in the question, will be achieved with this modified query.
Amit MohantyPosted Dec 19, 2023, 8:28 AM
Try this:
See this db<>fiddle : https://dbfiddle.uk/wVajzeVK