Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding months to a date in PostgreSQL shows syntax error

I am using Postgres 9.0 version. I want to add some months to a date to calculate the new date and update in a table. Here the number of months to be added will be in integer variable. My code is as follows:

declare numberofmonths smallint = 5; update salereg1 set expdate = current_date + interval cast(numberofmonths as text) month; 

The above code shows syntax error at cast. I don't know how to specify the numberofmonths variable as text.. can anyone help me. what is the mistake I did..

like image 845
Haji Avatar asked Sep 17 '13 13:09

Haji


People also ask

How do I format date in PostgreSQL?

Instead, you should use to_char to format the date when you query it, or format it in the client application. Like: SELECT to_char("date", 'DD/MM/YYYY') FROM mytable; e.g.

Does Postgres store dates as UTC?

PostgreSQL assumes your local time zone for any type containing only date or time. All timezone-aware dates and times are stored internally in UTC . They are converted to local time in the zone specified by the TimeZone configuration parameter before being displayed to the client.

How do I sort by month name in PostgreSQL?

The TO_DATE(birthday_month, 'Month') function converts a full month name to a date in the ' 0001-MM-01 ' format. For example, you get ' 0001-12-01 ' for December. You can now use the EXTRACT(MONTH FROM date) function to extract the month from this date value.


1 Answers

Try something like:

update salereg1  set expdate = current_date + interval '1 month' * numberofmonths; 
like image 82
Ihor Romanchenko Avatar answered Sep 25 '22 11:09

Ihor Romanchenko