如何在Oracle SQL查询语句中替换字符串内的日期参数为SYSDATE对应值
Got it, let's tackle this problem step by step. You want to swap those %y%m%d and %H%H date placeholders in your string column with actual values pulled from SYSDATE—here's how to do it cleanly in a SELECT query:
Core Approach: Nested REPLACE with TO_CHAR
Oracle's REPLACE function lets you swap specific substrings, and TO_CHAR converts SYSDATE into the exact string format you need for each placeholder. You'll nest multiple REPLACE calls to handle each placeholder one by one.
Example Query
Suppose your column is named file_name and your table is document_records. Here's the working query:
SELECT REPLACE( REPLACE(file_name, '%y%m%d', TO_CHAR(SYSDATE, 'YYMMDD')), '%H%H', TO_CHAR(SYSDATE, 'HH24') ) AS formatted_file_name FROM document_records;
Let's Break This Down
TO_CHAR(SYSDATE, 'YYMMDD'): ConvertsSYSDATEto a 6-character string like240520(for May 20, 2024). SwapYYwithYYYYif you need a 4-digit year (e.g.,20240520).TO_CHAR(SYSDATE, 'HH24'): ConvertsSYSDATE's hour to a 2-digit 24-hour format (e.g.,14for 2 PM,09for 9 AM).- Nested
REPLACE: First replaces%y%m%dwith the date string, then takes that result and replaces%H%Hwith the hour string. The order doesn't matter here—you could swap the inner and outerREPLACEcalls and get the same outcome.
Handling Extra Placeholders
If you have additional placeholders like %M%M (minutes) or %S%S (seconds), just add more nested REPLACE calls:
SELECT REPLACE( REPLACE( REPLACE(file_name, '%y%m%d', TO_CHAR(SYSDATE, 'YYMMDD')), '%H%H', TO_CHAR(SYSDATE, 'HH24') ), '%M%M', TO_CHAR(SYSDATE, 'MI') ) AS formatted_file_name FROM document_records;
Real-World Test Case
If your original string is SRK_ABC_%y%m%d_%H%H.txt and SYSDATE is 2024-05-20 16:45, the query will return:SRK_ABC_240520_16.txt
内容的提问来源于stack exchange,提问作者SRK

