Oracle SQL Multi Update - sql

Please Edit Pr Number
L3970076 to L3970276,
L3970077 to L3970277,
L3970078 to L3970278,
L3970080 to L3970280,
L3970082 to L3970282,
L3970083 to L3970283,
L3970085 to L3970285
SELECT * FROM GNGRB.PRFILE WHERE PRNO IN ('L3970076', 'L3970077', 'L3970078', 'L3970080', 'L3970082', 'L3970083', 'L3970085');
How to update it

Assuming that all the strings have the same length and that you always have to edit the 6th character into a '2', this could be enough:
update gngrb.prfile
set prno = substr(prno, 1, 5) || '2' || substr(prno, 7)
where ...

You seem to want a case expression:
update gngrb.prfile
set prno = case prno
when 'L3970076' then 'L3970276'
when 'L3970077' then 'L3970277'
when 'L3970078' then 'L3970278'
when 'L3970080' then 'L3970280'
when 'L3970082' then 'L3970282'
when 'L3970083' then 'L3970283'
when 'L3970085' then 'L3970285'
end
where prno in (
'L3970076',
'L3970077',
'L3970078',
'L3970080',
'L3970082',
'L3970083',
'L3970085'
);

You can use SUBSTR or REGEXP_REPLACE as follows:
UPDATE GNGRB.PRFILE
SET
PRNO = SUBSTR(PRNO,1) || (SUBSTR(PRNO,2) + 200)
--PRNO = REGEXP_REPLACE(PRNO ,'(^.{5})(0)([0-9]{2}$)','\12\3')
WHERE PRNO IN (
'L3970076',
'L3970077',
'L3970078',
'L3970080',
'L3970082',
'L3970083',
'L3970085'
);

Related

Remove special symbols from email string

I need to replace some characters in email string, exactly such actions:
lower_email = str.lower(str.split(email,'#')[0])
nopunc_email = re.sub('[!##$%^&*()-=+.,]', ' ', lower_email)
nonum_email = re.sub(r'[0-9]+', '', nopunc_email).strip()
But in SQL
I tried to use expression TRANSLATE(lower(email), 'a1_a.a-a#1-+()a ', 'a a a a'), but it didn't give me solution.
Thanks in advance!
For example:
import re
email = 'some_email.example-2021#gmail.com'
lower_email = str.lower(str.split(email,'#')[0])
nopunc_email = re.sub('[!#_#$%^&*()-=+.,]', ' ', lower_email)
nonum_email = re.sub(r'[0-9]+', '', nopunc_email).strip()
result 'some email example'
SELECT email,
TRIM(
TRANSLATE(
LOWER(SUBSTR(email, 1, INSTR(email, '#') - 1)),
'!_#$%^&*()-=+.,0123456789',
' '
)
) AS translated
FROM table_name
Which, for the sample data:
CREATE TABLE table_name (email) AS
SELECT 'some_email.example-2021#gmail.com' FROM DUAL;
Outputs:
EMAIL
TRANSLATED
some_email.example-2021#gmail.com
some email example
db<>fiddle here

update query to increment the existing value [duplicate]

I've read this thread: Issues incrementing a field in MySQL/PHP with prepared statements but didn't see the answer to my problem.
PDOStatement Object
(
[queryString] => UPDATE user_alerts SET notif = ? + 2 WHERE ( user_id = ? )
)
$stmt->execute( array( 'notif', '1' ) );
As far as I can tell, all this is correct.
When the above code executes, it sets the notif column equal to 2 irregardless of what the value of the notif column is. It's as if the SQL is reading like SET notif = 2 instead of SET notif = notif + 2
I haven't been able to figure it out and would really appreciate help!
$sql = 'UPDATE user_alerts SET notif = notif + 2 WHERE ( user_id = :userid )';
$prepStatement = $pdo->prepare( $sql );
$prepStatement->execute(array(':userid' => $userid));
You can't bind a column name to a prepared statement.
Using parameters is not just a simple text replacement. You can't replace a column name with a parameter. MySQL will interpret your query as if you had written this:
UPDATE user_alerts SET notif = 'notif' + 2 WHERE ( user_id = ? )
The string 'notif' is converted to zero for the addition.
Try this query instead:
UPDATE user_alerts SET notif = notif + 2 WHERE ( user_id = ? )

Optional parameters in cursor where clause

I have the following sample query which takes values from procedure parameters. The parameter can be either passed or default to null.
SELECT * FROM table
WHERE( table_term_code = '201931'
OR (table_term_code = '201931' and table_DETL_CODE ='CA02')
OR ( table_term_code = '201931' and table_ACTIVITY_DATE = sysdate)
OR ( table_term_code = '201931' and table_SEQNO = NULL));
i.e the user can input term code and not input any other parameter, or can input term code and table_DETL_CODE and not any other input parameter.
Same goes for the other 2 or conditions.
If a term code is passed and table_DETL_CODE is null, the query should return all the values for that term_code, whereas this query returns null.
Is there a way to achieve this without case or if conditions in PL/SQL?
If I understood you correctly, this might be what you're looking for:
select *
from your_table
where (table_term_code = :par_term_code or :par_term_code is null)
and (table_detl_code = :par_detl_code or :par_detl_code is null)
and (table_activity_date = :par_activity_date or :par_activity_date is null)
and (table_seqno = :par_seqno or :par_seqno is null)
The description seems to that you require user to enter table_term_code and then either none or exactly 1 of the other 3. If so then perhaps:
select *
from your_table
where table_term_code = :par_term_code
and ( (table_detl_code = :par_detl_code and :par_activity_date is null and :par_seqno is null)
or (table_activity_date = :par_activity_date and :par_detl_code is null and :par_seqno is null)
or (table_seqno = :par_seqno and :par_detl_code is null and :par_activity_date is null)
or (table_seqno is null and :par_detl_code is null and :par_activity_date is null)
);

how to cascade CASE sql inside the condition WHERE

I am searching for a word match for the variable- #TextSearchWord
I have a #SearchCriteria variable which may have 5 values!
According to that value, i choose from which field i have to search my word!
-so i need to cascade the "CASE" statement inside the "WHERE" statement only and like other samples here inside the select statement !
SELECT COUNT(WordID) AS WordQty
FROM itinfo_QuranArabicWordsAll
WHERE (SiteID = #SiteID)
AND (QuranID = #QuranID)
AND (SuraID BETWEEN #StrtSuraID AND #EndSuraID)
AND (VerseOrder BETWEEN #StrtVerseSortOrder AND #EndVerseSortOrder)
AND (
-- here is my problem :
CASE
WHEN (#SearchCriteria = 'DictNM') THEN (WordDictNM = #TextSearchWord )
ELSE CASE
WHEN (#SearchCriteria = 'DictNMAlif') THEN (WordDictNMAlif = #TextSearchWord)
...
END
END
)
You don't need a CASE statement for this.
SELECT COUNT(WordID) AS WordQty
FROM itinfo_QuranArabicWordsAll
WHERE (SiteID = #SiteID)
AND (QuranID = #QuranID)
AND (SuraID BETWEEN #StrtSuraID AND #EndSuraID)
AND (VerseOrder BETWEEN #StrtVerseSortOrder AND #EndVerseSortOrder)
AND (
(#SearchCriteria = 'DictNM' AND WordDictNM = #TextSearchWord )
OR (#SearchCriteria = 'DictNMAlif' AND WordDictNMAlif = #TextSearchWord)
...
)
SQL WHERE clauses: Avoid CASE, use Boolean logic.
....
AND(
( #SearchCriteria = 'DictNM' AND WordDictNM = #TextSearchWord )
OR ( #SearchCriteria = 'DictNMAlif' AND WordDictNMAlif = #TextSearchWord )
)

Update multiple rows in same query using PostgreSQL

I'm looking to update multiple rows in PostgreSQL in one statement. Is there a way to do something like the following?
UPDATE table
SET
column_a = 1 where column_b = '123',
column_a = 2 where column_b = '345'
You can also use update ... from syntax and use a mapping table. If you want to update more than one column, it's much more generalizable:
update test as t set
column_a = c.column_a
from (values
('123', 1),
('345', 2)
) as c(column_b, column_a)
where c.column_b = t.column_b;
You can add as many columns as you like:
update test as t set
column_a = c.column_a,
column_c = c.column_c
from (values
('123', 1, '---'),
('345', 2, '+++')
) as c(column_b, column_a, column_c)
where c.column_b = t.column_b;
sql fiddle demo
Based on the solution of #Roman, you can set multiple values:
update users as u set -- postgres FTW
email = u2.email,
first_name = u2.first_name,
last_name = u2.last_name
from (values
(1, 'hollis#weimann.biz', 'Hollis', 'Connell'),
(2, 'robert#duncan.info', 'Robert', 'Duncan')
) as u2(id, email, first_name, last_name)
where u2.id = u.id;
Yes, you can:
UPDATE foobar SET column_a = CASE
WHEN column_b = '123' THEN 1
WHEN column_b = '345' THEN 2
END
WHERE column_b IN ('123','345')
And working proof: http://sqlfiddle.com/#!2/97c7ea/1
For updating multiple rows in a single query, you can try this
UPDATE table_name
SET
column_1 = CASE WHEN any_column = value and any_column = value THEN column_1_value end,
column_2 = CASE WHEN any_column = value and any_column = value THEN column_2_value end,
column_3 = CASE WHEN any_column = value and any_column = value THEN column_3_value end,
.
.
.
column_n = CASE WHEN any_column = value and any_column = value THEN column_n_value end
if you don't need additional condition then remove and part of this query
Let's say you have an array of IDs and equivalent array of statuses - here is an example how to do this with a static SQL (a sql query that doesn't change due to different values) of the arrays :
drop table if exists results_dummy;
create table results_dummy (id int, status text, created_at timestamp default now(), updated_at timestamp default now());
-- populate table with dummy rows
insert into results_dummy
(id, status)
select unnest(array[1,2,3,4,5]::int[]) as id, unnest(array['a','b','c','d','e']::text[]) as status;
select * from results_dummy;
-- THE update of multiple rows with/by different values
update results_dummy as rd
set status=new.status, updated_at=now()
from (select unnest(array[1,2,5]::int[]) as id,unnest(array['a`','b`','e`']::text[]) as status) as new
where rd.id=new.id;
select * from results_dummy;
-- in code using **IDs** as first bind variable and **statuses** as the second bind variable:
update results_dummy as rd
set status=new.status, updated_at=now()
from (select unnest(:1::int[]) as id,unnest(:2::text[]) as status) as new
where rd.id=new.id;
Came across similar scenario and the CASE expression was useful to me.
UPDATE reports SET is_default =
case
when report_id = 123 then true
when report_id != 123 then false
end
WHERE account_id = 321;
Reports - is a table here, account_id is same for the report_ids mentioned above. The above query will set 1 record (the one which matches the condition) to true and all the non-matching ones to false.
The answer provided by #zero323 works great on Postgre 12. In case, someone has multiple values for column_b (referred in OP's question)
UPDATE conupdate SET orientation_status = CASE
when id in (66934, 39) then 66
when id in (66938, 49) then 77
END
WHERE id IN (66934, 39, 66938, 49)
In the above query, id is analogous to column_b; orientation_status is analogous to column_a of the question.
In addition to other answers, comments and documentation, the datatype cast can be placed on usage. This allows an easier copypasting:
update test as t set
column_a = c.column_a::number
from (values
('123', 1),
('345', 2)
) as c(column_b, column_a)
where t.column_b = c.column_b::text;
#Roman thank you for the solution, for anyone using node, I made this utility method to pump out a query string to update n columns with n records.
Sadly it only handles n records with the same columns so the recordRows param is pretty strict.
const payload = {
rows: [
{
id: 1,
ext_id: 3
},
{
id: 2,
ext_id: 3
},
{
id: 3,
ext_id: 3
} ,
{
id: 4,
ext_id: 3
}
]
};
var result = updateMultiple('t', payload);
console.log(result);
/*
qstring returned is:
UPDATE t AS t SET id = c.id, ext_id = c.ext_id FROM (VALUES (1,3),(2,3),(3,3),(4,3)) AS c(id,ext_id) WHERE c.id = t.id
*/
function updateMultiple(table, recordRows){
var valueSets = new Array();
var cSet = new Set();
var columns = new Array();
for (const [key, value] of Object.entries(recordRows.rows)) {
var groupArray = new Array();
for ( const [key2, value2] of Object.entries(recordRows.rows[key])){
if(!cSet.has(key2)){
cSet.add(`${key2}`);
columns.push(key2);
}
groupArray.push(`${value2}`);
}
valueSets.push(`(${groupArray.toString()})`);
}
var valueSetsString = valueSets.join();
var setMappings = new String();
for(var i = 0; i < columns.length; i++){
var fieldSet = columns[i];
setMappings += `${fieldSet} = c.${fieldSet}`;
if(i < columns.length -1){
setMappings += ', ';
}
}
var qstring = `UPDATE ${table} AS t SET ${setMappings} FROM (VALUES ${valueSetsString}) AS c(${columns}) WHERE c.id = t.id`;
return qstring;
}
I don't think the accepted answer is entirely correct. It is order dependent. Here is an example that will not work correctly with an approach from the answer.
create table xxx (
id varchar(64),
is_enabled boolean
);
insert into xxx (id, is_enabled) values ('1',true);
insert into xxx (id, is_enabled) values ('2',true);
insert into xxx (id, is_enabled) values ('3',true);
UPDATE public.xxx AS pns
SET is_enabled = u.is_enabled
FROM (
VALUES
(
'3',
false
,
'1',
true
,
'2',
false
)
) AS u(id, is_enabled)
WHERE u.id = pns.id;
select * from xxx;
So the question still stands, is there a way to do it in an order independent way?
---- after trying a few things this seems to be order independent
UPDATE public.xxx AS pns
SET is_enabled = u.is_enabled
FROM (
SELECT '3' as id, false as is_enabled UNION
SELECT '1' as id, true as is_enabled UNION
SELECT '2' as id, false as is_enabled
) as u
WHERE u.id = pns.id;