I'm trying to do the following. I have two tables, t_Vendor and Vendor_Load. I want to update the t_Vendor table with values from the Vendor_Load table. Comparing records between the two tables, if the vendor_number_tx matches, then update the fields in that record. If the vendor_number_tx doesn't match, or doesn't exist, insert a new record in the t_Vendor table.
I drafted up the following, which i know isn't efficient. I figure there must be a better way to write it. If you could help me, it would be great! It doesn't work because it says there's a missing expression and one of the sub selects returns more than one row anyway. Would this be better done in a stored proc?
I drafted up the following, which i know isn't efficient. I figure there must be a better way to write it. If you could help me, it would be great! It doesn't work because it says there's a missing expression and one of the sub selects returns more than one row anyway. Would this be better done in a stored proc?
Code:
/* update existing records into Vendor table if vendor number exists */
UPDATE t_vendor v
SET v.vendor_number_tx =
(SELECT vl.vendor_number_tx FROM vendor_load vl WHERE v.vendor_number_tx = vl.vendor_number_tx),
v.vendor_short_name_tx =
(SELECT vl.vendor_short_name_tx FROM vendor_load vl WHERE v.vendor_number_tx = vl.vendor_number_tx),
v.vendor_name_tx =
(SELECT vl.vendor_name_tx FROM vendor_load vl WHERE v.vendor_number_tx = vl.vendor_number_tx),
v.vendor_addr2_tx =
(SELECT vl.vendor_addr2_tx FROM vendor_load vl, vendor v WHERE v.vendor_number_tx = vl.vendor_number_tx),
v.vendor_addr3_tx =
(SELECT vl.vendor_addr3_tx FROM vendor_load vl, vendor v WHERE v.vendor_number_tx = vl.vendor_number_tx),
v.vendor_addr4_tx =
(SELECT vl.vendor_addr4_tx FROM vendor_load vl, vendor v WHERE v.vendor_number_tx = vl.vendor_number_tx),
v.vendor_addr5_tx =
(SELECT vl.vendor_addr5_tx FROM vendor_load vl, vendor v WHERE v.vendor_number_tx = vl.vendor_number_tx),
v.vendor_postal_code_tx =
(SELECT vl.vendor_postal_code_tx FROM vendor_load vl, vendor v WHERE v.vendor_number_tx = vl.vendor_number_tx)
WHERE
v.vendor_number_tx =
(SELECT vl.vendor_number_tx FROM vendor_load vl, vendor v WHERE v.vendor_number_tx = vl.vendor_number_tx);
COMMIT;
/* insert new records into Vendor table if vendor number does not exist */
INSERT INTO t_vendor v
(v.vendor_id_no, v.vendor_number_tx, v.vendor_short_name_tx, v.vendor_name_tx, v.vendor_addr2_tx, v.vendor_addr3_tx,
v.vendor_addr4_tx, v.vendor_addr5_tx, v.vendor_postal_code_tx)
VALUES
(
SELECT vl.vendor_number_tx, vl.vendor_short_name_tx, vl.vendor_name_tx, vl.vendor_addr2_tx, vl.vendor_addr3_tx,
vl.vendor_addr4_tx, vl.vendor_addr5_tx, vl.vendor_postal_code_tx
FROM vendor_load vl, t_vendor v
WHERE v.vendor_number_tx = vl.vendor_number_tx
AND v.vendor_number_tx <> (SELECT vl.vendor_number_tx FROM vendor_load vl, vendor v WHERE v.vendor_number_tx = vl.vendor_number_tx)
);
COMMIT;