How to solve Firebird searched case error inside a PSQL function [duplicate] - firebird

This question already has an answer here:
Error -104 creating Firebird stored procedure
(1 answer)
Closed 1 year ago.
I want to create a stored procedure in Firebird:
CREATE PROCEDURE CalcPvIncome
( BeginDate date,
EndDate date,
KwPrice decimal (2,2) )
RETURNS ( Total_PV_Production decimal (9,2),
Total_Income decimal (9,2) )
AS
BEGIN
FOR SELECT SUM(ENERGY/1000), SUM((ENERGY/1000) * :KwPrice)
FROM PVPROD
WHERE proddate >= :BeginDate AND proddate <= :Enddate
INTO :Total_PV_Production , :Total_Income
DO
BEGIN
SUSPEND ;
END
END
I get this error:
Engine Code : 335544569
Engine Message : Dynamic SQL Error SQL error code = -104 Unexpected end of command - line 18, column 9
The SQL statement:
SELECT
SUM(ENERGY/1000) AS Total_PV_Production,
sum((ENERGY/1000)*0.55) as Total_Income
FROM
PVPROD
where
proddate >= '12.06.2012' and proddate <= '12.07.2012'

You have to add SET TERM statement before and after the stored procedure. It is used to change the "terminator character". Here's an example:
SET TERM ^ ;
CREATE PROCEDURE CalcPvIncome
( BeginDate date,
EndDate date,
KwPrice decimal (2,2) )
RETURNS ( Total_PV_Production decimal (9,2),
Total_Income decimal (9,2) )
AS
BEGIN
...
END
SET TERM ; ^
Note that default terminator is ^ and also note that you are setting ; as new terminator before and resetting it back to ^ after stored procedure declaration.

Related

What is PostgreSQL equivalent for MSSQL STR ( float_expression [ , length [ , decimal ] ] ) function?

In MSSQL STR returns character data converted from numeric data. The character data is right-justified, with a specified length and decimal precision. SELECT STR(123.45, 6, 1) return ' 123.5' (not '123.5') in MSSQL. Also, SELECT STR(123.45, 2, 2) return '**' in MSSQL.
There is no direct corresponding Postgres function. You have a couple things going on: rounding at variable length, padding the result and result length validation. But easy enough to create your own SQL function: (see demo)
create or replace
function str(value_in numeric
,length_in integer default 7
,dec_len_in integer default 2
)
returns text
language sql
as $$
select case when length(val) > length_in
then rpad('*',length_in,'*') -- or just '**'
else lpad(val,length_in,'#') -- for demo using #, for real use ' '
end
from (select round(value_in, dec_len_in )::text) sq(val)
$$;

How to subtract dates in Oracle PL SQL

I'm using Oracle 18c.
I'm trying to determine elapsed time, but I get an error when I subtract two date variables in PL SQL.
The following code works fine:
DECLARE
l_zero_date date;
l_current_date date;
l_elapsed_time date;
BEGIN
Execute Immediate 'ALTER SESSION set nls_timestamp_format = "DD-MM-YYYY HH24:MI:SS"';
l_zero_date := to_date('01-01-1900 00:00:00', 'DD-MM-YYYY HH24:MI:SS');
dbms_output.put_line('The value of l_zero_date is: ' || l_zero_date);
Select ls.duration Into l_current_date From LIT_STATS ls Where ls.prim_key = 1002;
dbms_output.put_line('The value of l_curr_date is: ' || l_current_date);
-- dbms_output.put_line('The elapsed time is: ' || l_current_date - l_zero_date);
END;
This produces the results:
The value of l_zero_date is: 1900-01-01 00:00:00
The value of l_curr_date is: 1900-01-01 00:35:22
However, If I un-comment the last dbms_output line I get the error:
Error report -
ORA-06502: PL/SQL: numeric or value error: character to number conversion error
ORA-06512: at line 14
06502. 00000 - "PL/SQL: numeric or value error%s"
*Cause: An arithmetic, numeric, string, conversion, or constraint error
occurred. For example, this error occurs if an attempt is made to
assign the value NULL to a variable declared NOT NULL, or if an
attempt is made to assign an integer larger than 99 to a variable
declared NUMBER(2).
*Action: Change the data, how it is manipulated, or how it is declared so
that values do not violate constraints.
I don't understand why I get the error on subtraction involving two fields declared as DATE. For example, the following code works fine:
declare
a date;
b date;
begin
a := sysdate;
dbms_lock.sleep(10); -- sleep about 10 seconds give or take
b := sysdate;
dbms_output.put_line( b-a || ' of a day has elapsed' );
dbms_output.put_line( (b-a)*24 || ' of an hour has elapsed' );
dbms_output.put_line( (b-a)*24*60 || ' of a minute has elapsed' );
dbms_output.put_line( (b-a)*24*60*60 || ' seconds has elapsed' );
end;
Why does the line dbms_output.put_line('The elapsed time is: ' || l_current_date - l_zero_date); produce an error?
Thanks for looking at this.
As I mentioned in the comments, this is an order of operations issue. Take the following example:
SELECT 'TEST'||SYSDATE-SYSDATE FROM DUAL
When this runs, I get the following error: ORA-00932: inconsistent datatypes: expected CHAR got DATE
But when I wrap the dates in ( and ):
SELECT 'TEST'||(SYSDATE-SYSDATE) FROM DUAL
The result is TEST0.
It is order of operations, the code moves left to right unless there are parentheses informing it to do the date subtraction first.
Here is a DBFiddle showing the queries being run (LINK)

Can Firebirds SELECT FIRST accept a variable?

http://www.firebirdsql.org/refdocs/langrefupd20-select.html#langrefupd20-first-skip
The manual says that FIRST accepts "Any expression evaluating to an integer." Shouldn't this mean a variable too?
In the following stored procedure, I get an error trying to supply :DAYS to FIRST.
Token unknown - line 10, column 18
:
Line 10 column 18 is the : in front of DAYS...
SET TERM ^ ;
CREATE PROCEDURE P_STOCK_MDA
( STOCK BIGINT, TRADE_DATE DATE, DAYS SMALLINT )
RETURNS
( AVG_CLOSE NUMERIC(6,2) )
AS
BEGIN
SELECT AVG(STOCK_ADJ_CLOSE) FROM (
SELECT FIRST :DAYS STOCK_ADJ_CLOSE
FROM STOCK_DAILY yd
WHERE yd.STOCK_STOCK=:STOCK AND yd.TRADE_DATE<=:TRADE_DATE
ORDER BY yd.TRADE_DATE DESC
) INTO AVG_CLOSE;
END^
You need to enclose the parameter in parentheses to get it working:
SELECT FIRST (:DAYS) STOCK_ADJ_CLOSE
Full code:
SET TERM ^ ;
CREATE PROCEDURE P_STOCK_MDA
( STOCK BIGINT, TRADE_DATE DATE, DAYS SMALLINT )
RETURNS
( AVG_CLOSE NUMERIC(6,2) )
AS
BEGIN
SELECT AVG(STOCK_ADJ_CLOSE) FROM (
SELECT FIRST (:DAYS) STOCK_ADJ_CLOSE
FROM STOCK_DAILY yd
WHERE yd.STOCK_STOCK=:STOCK AND yd.TRADE_DATE<=:TRADE_DATE
ORDER BY yd.TRADE_DATE DESC
) INTO AVG_CLOSE;
END^
SET TERM ; ^
The documentation does say :
If <int-expr> is an integer literal or a query parameter, the “()” may be omitted
However I assume this only applies to the ? query parameter in DSQL, not to the named parameters in PSQL.

Convert a string representing a timestamp to an actual timestamp in PostgreSQL?

In PostgreSQL: I convert string to timestamp with to_timestamp():
select * from ms_secondaryhealthcarearea
where to_timestamp((COALESCE(update_datetime, '19900101010101'),'YYYYMMDDHH24MISS')
> to_timestamp('20121128191843','YYYYMMDDHH24MISS')
But I get this error:
ERROR: syntax error at end of input
LINE 1: ...H24MISS') >to_timestamp('20121128191843','YYYYMMDDHH24MISS')
^
********** Error **********
ERROR: syntax error at end of input
SQL state: 42601
Character: 176
Why? How to convert a string to timestamp?
One too many opening brackets. Try this:
select *
from ms_secondaryhealthcarearea
where to_timestamp(COALESCE(update_datetime, '19900101010101'),'YYYYMMDDHH24MISS') >to_timestamp('20121128191843','YYYYMMDDHH24MISS')
You had two opening brackets at to_timestamp:
where to_timestamp((COA.. -- <-- the second one is not needed!
#ppeterka has pointed out the syntax error.
The more pressing question is: Why store timestamp data as string to begin with? If your circumstances allow, consider converting the column to its proper type:
ALTER TABLE ms_secondaryhealthcarearea
ALTER COLUMN update_datetime TYPE timestamp
USING to_timestamp(update_datetime,'YYYYMMDDHH24MISS');
Or use timestamptz - depending on your requirements.
Another way to convert a string to a timestamp type of PostgreSql is the above,
SELECT to_timestamp('23-11-1986 06:30:00', 'DD-MM-YYYY hh24:mi:ss')::timestamp without time zone;
I had the same requirement as how I read the title. How to convert an epoch timestamp as text to a real timestamp. In my case I extracted one from a json object. So I ended up with a timestamp as text with milliseconds
'1528446110978' (GMT: Friday, June 8, 2018 8:21:50.978 AM)
This is what I tried. Just the latter (ts_ok_with_ms) is exactly right.
SELECT
data->>'expiration' AS expiration,
pg_typeof(data->>'expiration'),
-- to_timestamp(data->>'expiration'), < ERROR: function to_timestamp(text) does not exist
to_timestamp(
(data->>'expiration')::int8
) AS ts_wrong,
to_timestamp(
LEFT(
data->>'expiration',
10
)::int8
) AS ts_ok,
to_timestamp(
LEFT(
data->>'expiration',
10
)::int8
) + (
CASE
WHEN LENGTH(data->>'expiration') = 13
THEN RIGHT(data->>'expiration', 3) ELSE '0'
END||' ms')::interval AS ts_ok_with_ms
FROM (
SELECT '{"expiration": 1528446110978}'::json AS data
) dummy
This is the (transposed) record that is returned:
expiration 1528446110978
pg_typeof text
ts_wrong 50404-07-12 12:09:37.999872+00
ts_ok 2018-06-08 08:21:50+00
ts_ok_with_ms 2018-06-08 08:21:50.978+00
I'm sure I overlooked a simpler version of how to get from a timestamp string in a json object to a real timestamp with ms (ts_ok_with_ms), but I hope this helps nonetheless.
Update: Here's a function for your convenience.
CREATE OR REPLACE FUNCTION data.timestamp_from_text(ts text)
RETURNS timestamptz
LANGUAGE SQL AS
$$
SELECT to_timestamp(LEFT(ts, 10)::int8) +
(
CASE
WHEN LENGTH(ts) = 13
THEN RIGHT(ts, 3) ELSE '0'
END||' ms'
)::interval
$$;

How to make a function in DB2 database to convert an integer to date, and the case when is 0?

I was trying to make a function to work in db2:
CREATE FUNCTION TO_DATE8(DATE_STRING numeric(8,0))
RETURNS DATE
LANGUAGE SQL
IF DATE_STRING > 0 THEN
// ERROR ->
RETURN DATE ( TO_DATE ( SUBSTR ( DATE_STRING , 1 , 8 ) , 'YYYYMMDD' ) )
ELSE
RETURN DATE ( TO_DATE ( '00000000' , 'YYYYMMDD' ) )
END IF
END
ERROR: DATE IS NOT VALID
What to do?
The form of the procedure required seems to be like this (at least on the iSeries version):
CREATE FUNCTION TO_DATE8(DATE_STRING numeric(8,0))
RETURNS DATE
LANGUAGE SQL
BEGIN
RETURN(CASE WHEN DATE_STRING > 0 THEN DATE(SUBSTR(DATE_STRING, 1, 4) || '-' ||
SUBSTR(DATE_STRING, 5, 2) || '-' ||
SUBSTR(DATE_STRING, 7, 2))
ELSE DATE('0001-01-01')
END);
END
However:
Your procedure is misnamed (reading from a date-8, not to it).
Your DATE_STRING is not a string (or even a char), it's numeric. Please rename it to something that does not include the datatype (dateToConvert works)
You seem to want to return something that is not a valid date (all 0s). I'm returning *loval here, although it's possible it should actually be null.
I didn't put in enough checks for a valid date - this will blow up really easily.
If at all possible, the database should be changed to contain actual dates, not a numeric value. Disk is (relative to programmer/architect headaches) cheap.
You may also find a calendar file helpful, if the 8-digit numeric was one of the included columns.
For the benifit of others, this can be done in one line rather than a function:
CASE WHEN MYDATE = 0 THEN NULL ELSE DATE(INSERT(INSERT(LEFT(CHAR(MYDATE),8),5,0,'-'),8,0,'-')) END
MYDATE was 8 packed in my case.