Mapping ID values using SQL - sql-server

Assume you have 2 DB with matching table structures in both.
For example,
D1.T1(ID, VAL) = D2.T1(ID,VAL)
D1.T2(ID, NAME,FID) = D2.T2(ID, NAME,FID)
Where D1.T2.FID = D1.T1.ID
Now I want to copy rows from D1 to D2. But ID values changes during the insert into D2 (not because I can't force insert the same ID by using IDENTITY_INSERT, its because the same ID exist in D2.T1 for some other values).
Now I need to update the D2.T2 with the new identity values. How can this be done, without altering tables (to persist the old_id value in D2.T1 and doing an update later on on D2.T2 by comparing the old id value)?
To give a hint of the tables structure see below.
D1.T1
ID, VAL
4934, A
4936, B
5011, C
D1.T2
ID, NAME, FKID
2478, I, 4934
2479, II, 4936
2481, III, 5011
D2.T1
ID, VAL
7813, A
7817, B
7819, C
D2.T2
ID, NAME, FKID
3416, I, 7813
3417, II, 7817
3419, III, 7819

So, for example, we now come across a
D1.T1 of 7813, D
and then discover that 7813 already exists in D2.T1??
"But ID values change during the insert into D2"
What does it change to? say 9876 ?? So now D2.T1 would be 9876, D
Well, lets go on and try to copy
D1.T2 of 2482, IIII, 7813
BUT WAIT >> How do we know if this 7813 refers to 7813, A or 7813, D
We don't know, We cannot determine if we need to keep 7813 or change to 9876.
Ergo, we need more information that resides in the table, e.g. another column.

Related

SQL Server - selecting a specific ID from a table

I will explain what I have done so far and ask my question at the end.
First I created my external & internal variables (note that #EDelivery is a table type that included the columns FoodID and Quantity):
#EDelivery DeliveryTblType readonly
Declare #NumberOfMinutes smallint, #FoodWeight int, #WeightCapacity int,
#DroneID int, #TimeOfWeek varchar
I then read this in, giving me the total weight of all items ordered and read in the weight capacity from the DronesTbl:
select #FoodWeight = SUM(FoodWeight * Quantity)
from #EDelivery as del
inner join Foods on del.FoodID = Foods.FoodID
select #WeightCapacity = Drones.WeightCapacity
from dbo.Drones
My question is how do I select a specific drone to compare its weightcapacity to the food total weight
You need to set the variable #WeightCapacity according to the #droneid value. Right now, you are setting this variable to last drone in your drones table.
If you change your second query to what's below then it should work.
select #WeightCapacity =
Drones.WeightCapacity
from dbo.Drones
where DroneID =#droneID

Updating one table's column in SQL Server from another

I have a table of measurements from weather stations, with station names (in Hebrew):
I also have created a table of those weather stations with their latitudes and longitudes:
I've written a query that should update the first table with the lat/longs from the second, but it's not working:
update t1
set t1.MeasurementLat = t2.Latitude,
t1.MeasurementLong = t2.Longitude
from [dbo].[Measurements] as t1
inner join [dbo].[StationCoords] as t2 on t1.StationName like t2.Station
I think there is a problem with the way the station name is being read, and perhaps something to do with encoding, because this query brings back an empty result, too:
SELECT TOP (5) *
FROM [dbo].[Measurements]
WHERE [StationName] = 'אריאל מכללה';
Any ideas?
Your example names are not the same. Perhaps this will work:
update m
set MeasurementLat = sc.Latitude,
MeasurementLong = sc.Longitude
from dbo.[Measurements] m join
dbo.[StationCoords] sc
on m.StationName like sc.Station + '%';

Totalling up values across salesforce account hierarchies

I'm struggling to find an approach to the following problem, can anyone suggest a high level approach.
Using talend, I have an input set of values for a set of accounts (from CSV):
AccountId, ValueXYZ__c
I want to store ValueXYZ against the SFDC account, which is no problem, but then I want to totalise ValueXYZ up for all the accounts with the same parent to
Account.Parent.TotalValueXYZ
I then want to "roll" this all the way up the accounts hierarchy:
Imagine account hierarchy:
A
-B
--C
--D
-E
--F
--G
I want 3 values on A:
ValueXYZ = account A's ValueXYZ
TotalValueXYZ = total of ValueXYZ values for all accounts under A in the hierarchy
TOTAL = formula field to add together the previous 2 values
I want 3 values on account B
ValueXYZ = account B's ValueXYZ
TotalValueXYZ = total of ValueXYZ values for accounts C & D
TOTAL = formula field to add together the previous 2 values
I want 3 values on account C
ValueXYZ = account C's ValueXYZ
TotalValueXYZ = 0
TOTAL = formula field to add together the previous 2 values
I've tried several approaches, but can't get any of them to work!
Where is the hierarchy information stored? If you can flatten the hierarchy information in a key-value pair format, then it is straightforward. Just read your input file and do a lookup/join on the hierarchy file. You will have to loop through until you get to the base record
The crux of my problem was in not knowing each accounts position in a hierarchy. Once I had that in place, I could loop from the lowest level to the highest level, totalling these values up to their parents.
Here is the T-SQL I wrote to mark each account with it's Hierarchy Position (HILEVEL)
TRUNCATE TABLE [TALEND_WORKSPACE].[dbo].[SFDCAccount]
INSERT INTO [TALEND_WORKSPACE].[dbo].[SFDCAccount] (Id, ParentId, QCIYTDOneTime, QCIYTDRecurring, HILEVEL)
SELECT Id, ParentId, ValueXYZ, '0'
FROM [TALEND_WORKSPACE].[dbo].[SFDCAccountRawData]
WHERE ParentId = ' ';
USE TALEND_WORKSPACE
IF OBJECT_ID('dbo.sfdcaccounthierarchy', 'P') IS NOT NULL
DROP PROCEDURE [dbo].[sfdcaccounthierarchy];
GO
CREATE PROCEDURE [dbo].[sfdcaccounthierarchy]
AS
DECLARE #v_counter int;
DECLARE #v_lastccounter int;
DECLARE #v_max int;
SET #v_counter = 0;
SET #v_lastccounter = 0;
SET #v_max = 10;
WHILE (#v_counter < #v_max)
BEGIN
SET #v_lastccounter = #v_counter;
SET #v_counter = #v_counter+1;
PRINT #v_counter;
INSERT INTO [dbo].[SFDCAccount] (Id, ParentId, QCIYTDOneTime, QCIYTDRecurring, HILEVEL)
SELECT Id, ParentId, ValueXYZ, #v_counter
FROM [TALEND_WORKSPACE].[dbo].[SFDCAccountRawData]
WHERE ParentId IN (SELECT Id FROM [TALEND_WORKSPACE].[dbo].[SFDCAccount]
WHERE HILEVEL = #v_lastccounter);
if ##ROWCOUNT != 0
BREAK;
END
GO
EXEC [TALEND_WORKSPACE].[dbo].[sfdcaccounthierarchy];

Retriving data from different tables depending on value in a column

Please pardon me if this question has been asked before, but I simply don't have enough vocabulary to search for what I need as a novice in data bases.
I am using SQL server 2008.
I have a table tblPDCDetails with several columns. One of the columns PDCof holds values :
"A"(for applicant),
"C" for coapplicant,
"G" (for Guarantor).
Another column HolderID holds uniqueid (of holder).
The PDCHolders reside in their respective tables: Applicants in tblApplBasicDetails, CoApllicants in their own table and so on.
Now what I need is how should I retrive the names of holders from their respective tables, depending on the value in PDCof column.
Can I do it at all?
If no how should I work around this?
This should do:
SELECT A.*,
COALESCE(B.Name,C.Name,D.Name) Name
FROM dbo.tblPDCDetails A
LEFT JOIN dbo.tblApplBasicDetails B
ON A.HolderID = B.HolderID
AND A.PDCof = 'A'
LEFT JOIN dbo.tblCoApplBasicDetails C
ON A.HolderID = C.HolderID
AND A.PDCof = 'C'
LEFT JOIN dbo.tblGuarantorlBasicDetails D
ON A.HolderID = D.HolderID
AND A.PDCof = 'G'
The other option is to use a case switch:
Select case Main.PDCof
when 'A' then (select HolderID from Applicants where main.value = value)
when 'C' then (select HolderID from CoApplicants where main.value = value)
when 'G' then (select HolderID from Guarantor where main.value = value)
end
,main.*
from tblPDCDetails main
Depends on whether you run this a few times a day, or a few thousand times an hour

Oracle Triggers Update at Another Table

I am trying to create a trigger in Oracle. I know sql but i have never created trigger before. I have this code:
create or replace trigger "PASSENGER_BOOKING_T1"
AFTER
insert on "PASSENGER_BOOKING"
for each row
begin
IF (:NEW.CLASS_TYPE == 'ECO')
SELECT F.AVL_SEATS_ECOCLASS,F.FLIGHT_ID INTO SEAT, FLIGHT_INFO
FROM BOOKING B, JOURNEY_FLIGHT J, FLIGHT F
WHERE B.JOURNEY_ID = J.JOURNEY_ID and F.FLIGHT_ID = J.FLIGHT_ID;
UPDATE FLIGHT
SET AVL_SEATS_ECOCLASS = (SEAT-1)
WHERE FLIGHT_ID = FLIGHT_INFO;
END IF;
end;​
This trigger fires when there is an insert in Passenger_Booking table. And seating capacity is reduced by one (which is at different table).
Select query should be alright but there is something wrong in somewhere.
Could anyone suggest anything?
I changed the body part to this but still having issues:
UPDATE FLIGHT
SET AVL_SEATS_ECOCLASS =
(SELECT F.AVL_SEATS_ECOCLASS FROM BOOKING B, JOURNEY_FLIGHT J, FLIGHT F WHERE B.JOURNEY_ID = J.JOURNEY_ID and F.FLIGHT_ID = J.FLIGHT_ID;
);
An IF statement needs a THEN
In PL/SQL, you use an = to test for equality, not ==
You need to declare the variables that you are selecting into
When I do those three things, I get something like this
create or replace trigger PASSENGER_BOOKING_T1
AFTER insert on PASSENGER_BOOKING
for each row
declare
l_seat flight.seat%type;
l_flight_id flight.flight_id%type;
begin
IF (:NEW.CLASS_TYPE = 'ECO')
THEN
SELECT F.AVL_SEATS_ECOCLASS,F.FLIGHT_ID
INTO l_seat, l_flight_id
FROM BOOKING B,
JOURNEY_FLIGHT J,
FLIGHT F
WHERE B.JOURNEY_ID = J.JOURNEY_ID
and F.FLIGHT_ID = J.FLIGHT_ID;
UPDATE FLIGHT
SET AVL_SEATS_ECOCLASS = (l_seat-1)
WHERE FLIGHT_ID = l_flight_id;
END IF;
end;​
Beyond those syntax errors, I would be shocked if the SELECT INTO statement was correct. A SELECT INTO must return exactly 1 row. Your query should almost certainly return multiple rows since there are no predicates that would restrict the query to a particular flight or a particular booking. Presumably, you want to join to one or more columns in the PASSENGER_BOOKING table.
Additionally, if this is something other than a homework assignment, make sure you understand that this sort of trigger does not work correctly in a multi-user environment.
just a wild guess
edit as Justin pointed out (thanks Justin) equality check
create or replace trigger "PASSENGER_BOOKING_T1"
AFTER
insert on "PASSENGER_BOOKING"
for each row
declare
v_flight_id FLIGHT.FLIGHT_ID%TYPE;
begin
IF (:NEW.CLASS_TYPE = 'ECO') THEN
SELECT F.ID into v_flight_id
FROM BOOKING B, JOURNEY_FLIGHT J, FLIGHT F
WHERE B.ID = :NEW.BOOKING_ID -- note that I've made this up
AND B.JOURNEY_ID = J.JOURNEY_ID AND F.FLIGHT_ID = J.FLIGHT_ID;
UPDATE FLIGHT
SET AVL_SEATS_ECOCLASS = (SEAT-1)
WHERE ID = v_flight_id;
END IF;
end;​

Resources