Change datatype from DATE to VARCHAR()
-
03-03-2021 - |
Question
CREATE OR REPLACE procedure create_table_dateWise27()
LANGUAGE plpgsql
as $$
declare
d_date date;
begin
select to_char(current_timestamp :: timestamp - interval '1 hour','yyyy-mm-
dd')into d_date;
EXECUTE format('
CREATE TABLE IF NOT EXISTS %I(
nodeip text,
interface text,
nodeip_interface text
)','test_'|| d_date-1);
commit;
end;
$$;
call create_table_dateWise27();
I want to perform the same operation where d_date is a VARCHAR().
Solution
If you want to put yesterday's date into the variable then do it during assignment. And if you want a varchar, then declare it as one - your current code does an implicit and useless conversion back a varchar back to a date
anyway.
So something like:
CREATE OR REPLACE procedure create_table_dateWise27()
LANGUAGE plpgsql
as $$
declare
d_date varchar;
begin
d_date := to_char(current_date - 1, 'yyyy_mm_dd'); --<< yesterday
EXECUTE format('
CREATE TABLE IF NOT EXISTS %I(
nodeip text,
interface text,
nodeip_interface text
)','test_'|| d_date);
commit;
end;
$$;
Note that I changed the format mask for the to_char()
call to use underscores (_
) rather than -
because a dash is invalid in an SQL identifier (table name) and thus would require the use of a quoted identifier which you should really avoid.
Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange