Home >Database >Mysql Tutorial >How to Dynamically Assign Set Names Based on Date Ranges in SQL?
Splitting Given String
To split the given dates represented by p_dates, use a regular expression to extract date ranges within brackets. For example:
SELECT string_to_array(p_dates, '[,]+') AS dates;
Splitting Given Sets
Use a similar regular expression to split the sets in p_sets using commas as the delimiter:
SELECT string_to_array(p_sets, '[,]+') AS sets;
Preparing Dynamic Case Statement
With the split dates and sets, construct a dynamic case statement using a loop:
DECLARE dates CHAR[], sets CHAR[]; BEGIN -- Get split dates and sets SELECT * INTO dates, sets FROM ( SELECT string_to_array(p_dates, '[,]+') AS dates, string_to_array(p_sets, '[,]+') AS sets ); -- Loop through each pair of date range and set FOR i IN 1..ARRAY_UPPER(sets) LOOP -- Construct CASE statement CASE WHEN given_dates BETWEEN split_part(dates[i], 'to', 1) AND split_part(dates[i], 'to', 2) THEN sets[i] END END CASE; END;
This will generate a dynamic CASE statement that assigns set names based on the date ranges.
The above is the detailed content of How to Dynamically Assign Set Names Based on Date Ranges in SQL?. For more information, please follow other related articles on the PHP Chinese website!