SQL Server MERGE, if exist then update else insert - sql

I've a table called data with columns ip, report_date, group, value. The primary key is ip, report_date and group together.
When the table is empty and I run the statement below there is nothing inserted. What's wrong with my statement?
When there is a match the record is updates according plan...
MERGE bc_data2 AS Target
USING (SELECT ip, report_date, group, value FROM bc_data2 As b
WHERE b.ip = '1.1.1.2'
AND b.report_date = '2/29/2012'
AND b.group = 'EPO-Client-Update') AS Source
ON (Target.ip = Source.ip
AND Target.frequency = Source.frequency
AND Target.report_date = Source.report_date
AND Target.service = Source.service
AND Target.proxy_service = Source.proxy_service
AND Target.proxy = Source.proxy
AND Target.service_group = Source.service_group)
WHEN MATCHED THEN
UPDATE SET Target.value = Target.value + 1
WHEN NOT MATCHED BY Target THEN
INSERT (ip, report_date, group, value)
VALUES ('1.1.1.2', '2/29/2012', 'EPO-Client-Update', 119437142);

You don't add any rows because your using clause is not returning any rows. Put your constants in the using clause with column aliases and use the fields in the when not matched
Something like this with a couple of fields removed simplicity.
merge bc_data2 as T
using (select '1.1.1.2' as ip,
'2012-02-29' as report_date,
1194370142 as value) as S
on T.ip = S.ip and
T.report_date = S.report_date
when matched then
update set T.value = T.value + 1
when not matched then
insert (ip, report_date, value)
values(ip, report_date, value);

I've found that NULLs don't compare well in the ON clause of the MERGE statement. However, converting NULLs to blanks is a valid workaround. I would modify the the ON statement to look something like this.
ON (ISNULL(Target.ip, '') = ISNULL(Source.ip, '')
AND ISNULL(Target.frequency, '') = ISNULL(Source.frequency, '')
AND ISNULL(Target.report_date, '') = ISNULL(Source.report_date, '')
AND ...)

Related

DB2 LUW MERGE using same table to update a different row

My table data looks like this
My poorly attempted SQL is this...
MERGE INTO PRINT target
USING
(
select ID,PDF_FILE
from PRINT
where date(PRINTED) = '2022-01-06'
and PDF_FILE is not null
) sause
ON (target.ID = sause.ID)
WHEN MATCHED THEN
UPDATE SET target.PDF_FILE = sause.PDF_FILE
It is updating all rows in the table. I do not want this.
How can I make it ONLY update the 1 latest PRINTED row which has an empty PDF_FILE ?
The idea is to enumerate target rows and update only the 1-st one.
MERGE INTO
(
SELECT ID, PDF_FILE, ROW_NUMBER () OVER (PARTITION BY ID ORDER BY PRINTED DESC) AS RN_
FROM PRINT
WHERE
-- Below is an appropriate condition for
-- the target rows to distinguish them from the source row
-- PDF_FILE IS NULL
date (PRINTED) <> '2022-01-06'
) target
USING
(
select ID,PDF_FILE
from PRINT
where date (PRINTED) = '2022-01-06'
and PDF_FILE is not null
) sause
ON target.ID = sause.ID AND target.RN_ = 1
WHEN MATCHED THEN
UPDATE SET target.PDF_FILE = sause.PDF_FILE

select subquery using data from the select statement?

I have two tables, headers and lines. I need to grab the batch_submission_date from the header table, but sometimes a query for batch_id will return a null for batch_submission_date, but will also return a parent_batch_id, and if we query THAT parent_batch_id as a batch_id, it will then return the correct batch_submission_date.
e.g.
SELECT t1.batch_id,
t1.parent_batch_id,
t2.batch_submission_date
FROM db.headers t1, db.lines t2
WHERE t1.batch_id = '12345';
output = 12345, 99999, null
Then we use that parent batch_id as a batch_id :
SELECT t1.batch_id,
t1.parent_batch_id,
t2.batch_submission_date
FROM db.headers t1, db.lines t2
WHERE t1.batch_id = '99999';
and we get output = 99999,99999,'2018-01-01'
So I'm trying to write a query that will do this for me - anytime a batch_id's batch_submission_date is null, we find that batch_id's parent batch_id and query that instead.
This was my idea - but I just get back null both for bp_batch_submission_date and for new_submission_date.
SELECT
t1.parent_id as parent_id,
t1.BATCH_ID as bp_batch_id,
t2.BATCH_LINE_NUMBER as bp_batch_li,
t1.BATCH_SUBMISSION_DATE as bp_batch_submission_date,
CASE
WHEN t1.BATCH_SUBMISSION_DATE is null
THEN
(SELECT a.BATCH_SUBMISSION_DATE
FROM
db.headers a,
db.lines b
WHERE
a.SD_BATCH_HEADERS_SKEY = b.SD_BATCH_HEADERS_SKEY
and a.parent_batch_id = bp_batch_id
and b.batch_line_number = bp_batch_li
) END as new_submission_date
FROM
db.headers t1,
db.lines t2
WHERE
t1.SD_BATCH_HEADERS_SKEY = t2.SD_BATCH_HEADERS_SKEY
and (t1.BATCH_ID = '12345' or t1.PARENT_BATCH_ID = '12345')
and t2.BATCH_LINE_NUMBER = '1'
GROUP BY
t2.BATCH_CLAIM_LINE_STATUS_DESC,
t1.PARENT_BATCH_ID,
t1.BATCH_ID,
t2.BATCH_LINE_NUMBER,
t1.BATCH_SUBMISSION_DATE;
is what I'm trying to do possible? using the bp_batch_id and bp_batch_li variables
Use CTE (common table expression) to avoid redundant code, then use coalesce() to find parent date in case of null. In your first queries you didn't attach joining condition between two tables, I assumed it's based on sd_batch_headers_skey like in last query.
dbfiddle demo
with t as (
select h.batch_id, h.parent_batch_id, l.batch_submission_date bs_date
from headers h
join lines l on l.sd_batch_headers_skey = h.sd_batch_headers_skey
and l.batch_line_number = '1' )
select batch_id, parent_batch_id,
coalesce(bs_date, (select bs_date from t x where x.batch_id = t.parent_batch_id)) bs_date
from t
where batch_id = 12345;
You could use simpler syntax with connect by and level <= 2 but if in your data there are really rows containing same ids (99999, 99999) then we get cycle error.

How do I UPDATE from a SELECT in Informix?

I'm trying to do an update using data from another table. I've tried this answer (the second part), but it is not working for me. I'm receiving a generic error message of syntax error.
I've also tried this solution and received a syntax error message too.
If I try to update just one column, it works:
UPDATE dogs
SET name =
(
SELECT 'Buddy'
FROM systables
WHERE tabid = 1
);
But I need to update multiples columns. Unfortunately, this is not working:
UPDATE dogs
SET (name, breed) =
(
SELECT 'Buddy', 'pug'
FROM systables
WHERE tabid = 1
);
Informix version is 12.10.FC8
You are missing 1 more set of parentheses around the subquery.
From the Informix manual:
The subquery must be enclosed between parentheses. These parentheses
are nested within the parentheses that immediately follow the equal (
= ) sign. If the expression list includes multiple subqueries, each subquery must be enclosed between parentheses, with a comma ( , )
separating successive subqueries:
UPDATE ... SET ... = ((subqueryA),(subqueryB), ... (subqueryN))
The following examples show the use of subqueries in the SET clause:
UPDATE items
SET (stock_num, manu_code, quantity) =
(
(
SELECT stock_num, manu_code
FROM stock
WHERE description = 'baseball'
),
2
)
WHERE item_num = 1 AND order_num = 1001;
UPDATE table1
SET (col1, col2, col3) =
(
(
SELECT MIN (ship_charge), MAX (ship_charge)
FROM orders
),
'07/01/2007'
)
WHERE col4 = 1001;
So in order for your update to be accepted by Informix it has to be:
UPDATE dogs
SET (name, breed) =
(
(
SELECT 'Buddy', 'pug'
FROM systables
WHERE tabid = 1
)
);

How to add results of a SELECT to a table

I have a SQL select statement which is comparing two tables. I am getting the values where the rows are the same. Now I have got this in the procedure I need to add these into a new table (coftReconciliationMatches). The table has all the same columns but one additional one 'MatchOrNoMatch'. I need to pass through the values of the row that are matched and also need to pass through 'Match' to the column 'MatchOrNoMatch'
This is the current part of the SQL script I have;
SELECT *
FROM dbo.coftReconciliationFileInfo AS a
WHERE EXISTS (SELECT *
FROM dbo.coftPreReconciliationInfo AS b
WHERE a.Rec_PK = b.Rec_PK
AND a.ExtRef1 = b.ExtRef1
AND a.SedolRef = b.SedolRef
AND a.ValLatest = b.ValLatest
AND a.Totunits = b.Totunits
AND a.FundsOrCash = b.FundsOrCash )
When comparing a lot of columns, the SELECT INTERSECT and SELECT EXCEPT commands can save you a lot of effort:
INSERT dbo.coftReconcilliationMatches
(Rec_PK, ExtRef1, SedolRef, ValLatest, Totunits, FundsOrCash, MatchOrNoMatch)
select Rec_PK, ExtRef1, SedolRef, ValLatest, Totunits, FundsOrCash, 'Match'
from dbo.coftReconciliationFileInfo
intersect select Rec_PK, ExtRef1, SedolRef, ValLatest, Totunits, FundsOrCash, 'Match'
from dbo.coftPreReconciliationFileInfo
(Check for typos!)
If you are creating the table on the fly (something I wouldn't recommend doing), you'd use SELECT INTO.
INSERT INTO [table] ([col1], [col2]) SELECT colx, ...
Use Select Into for this. See here http://www.w3schools.com/sql/sql_select_into.asp
Try something like:
INSERT INTO <your table> (<list of columns>)
SELECT <list of columns from select>, '<the additional column>' FROM dbo.coftReconciliationFileInfo AS a
WHERE EXISTS(SELECT * FROM dbo.coftPreReconciliationInfo AS b
WHERE a.Rec_PK = b.Rec_PK AND a.ExtRef1 = b.ExtRef1 AND a.SedolRef = b.SedolRef AND a.ValLatest = b.ValLatest AND a.Totunits = b.Totunits AND a.FundsOrCash = b.FundsOrCash )
also see http://www.1keydata.com/sql/sqlinsert.html
you need to do:
INSERT INTO Table (column1, column2..)
(SELECT column1, column2 ....
FROM dbo.coftReconciliationFileInfo AS a
WHERE EXISTS (SELECT *
FROM dbo.coftPreReconciliationInfo AS b
WHERE a.Rec_PK = b.Rec_PK
AND a.ExtRef1 = b.ExtRef1
AND a.SedolRef = b.SedolRef
AND a.ValLatest = b.ValLatest
AND a.Totunits = b.Totunits
AND a.FundsOrCash = b.FundsOrCash ))

sql server query how to have multiple column comparision with subquery

How can I make the update query to work based on the sub query?
How can I compare all these columns in the sub query to the columns in the update statement?
Is there some neat and clean way to do it?
The query I am trying with it is shown below:
UPDATE Temp_CropData
SET RecordStatus = 0,
Remarks = ISNULL(Remarks, '') +' Duplicate Records'
WHERE
(SELECT Commodity ,City,Period,CropCondition
FROM [Temp_CropData]
GROUP BY DDate,Commodity,City,Period,CropCondition
HAVING count(*) >1)
Try using MERGE:
MERGE INTO Temp_CropData
USING (
SELECT Commodity, City, Period, CropCondition
FROM Temp_CropData
GROUP
BY DDate, Commodity, City, Period, CropCondition
HAVING COUNT(*) > 1
) AS source
ON Temp_CropData.Commodity = source.Commodity
AND Temp_CropData.City = source.City
AND Temp_CropData.Period = source.Period
AND Temp_CropData.CropCondition = source.CropCondition
WHEN MATCHED THEN
UPDATE
SET RecordStatus = 0,
Remarks = ISNULL(Remarks, '') + ' Duplicate Records';
I'm slightly suspicious of the fact that your subquery's SELECT and GROUP BY clauses do not match, though (i.e. DDate is in the GROUP BY but not the SELECT).
Try this:
UPDATE cd
SET RecordStatus = 0,
Remarks = ISNULL(Remarks, '') +' Duplicate Records'
FROM Temp_CropData cd
JOIN (SELECT Commodity ,City,Period,CropCondition
FROM [Temp_CropData]
GROUP BY DDate,Commodity,City,Period,CropCondition
HAVING count(*) >1) dup
ON cd.DDate = dup.DDate AND cd.Commodity=dup.Commodity AND cd.City = dup.City
AND cd.Period = dup.Period AND cd.CropCondition = dup.CropCondition