Table: table_name
create table table_name
(
given_dates timestamp,
set_name varchar
);
Insertion of records:
insert into table_name values('2001-01-01'),('2001-01-05'),('2001-01-10'),
('2001-01-15'),('2001-01-20'),('2001-01-25'),
('2001-02-01'),('2001-02-05'),('2001-02-10'),
('2001-02-15');
Now I want to update set_name for some dates.
For example:
I want to update table like this:
given_dates set_name
----------------------
2001-01-01 s1
2001-01-05 s1
2001-01-10 s2
2001-01-15 s2
2001-01-20
2001-01-25
2001-02-01
2001-02-05
2001-02-10
2001-02-15
Note: The given_dates
and set_name
are pass a parameter because of they are dynamic. I may pass 2 sets
as shown above s1,s2
or may pass 4 sets according to the requirement.
So I need the dynamic case statement for update the set_name
.
Given two parameters:
declare p_dates varchar := '2001-01-01to2001-01-05,2001-01-10to2001-01-15';
declare p_sets varchar := 's1,s2';
Well I can do this by using following static script:
Static Update statement:
update table_name
SET set_name =
CASE
when given_dates between '2001-01-01' and '2001-01-05' then 's1'
when given_dates between '2001-01-10' and '2001-01-15' then 's2'
else ''
end;
The above update statement does the job done but statically.
Like the same way to update table I want to prepare only case statement which should be dynamic which can change as per the parameters (p_dates,p_sets)
changes.
Questions:
- How to split the given dates that is
p_dates
? (I haveto
keyword in between two dates.) - How to split the given sets that is
p_sets
? (I have ',' comma in between two set_names.) - How to prepare dynamic case statement after splitting the
p_dates
andp_sets
?
This question relates to Dynamic case statement using SQL Server 2008 R2, which is the same thing but for Microsoft SQL Server.
string_to_array()
function: postgresql.org/docs/current/static/functions-array.html – Heelandtoe