How to pass bash date into sql timestamp - sql

Hello i have code like this:
...AND o.creation_date > TO_DATE($DATE_TODAY, 'YYYYMMDD')...
When i want to pass variable into function TO_DATE it works.
But in another script, I have code like this...
...AND o.creation_date > TO_TIMESTAMP( $DATE_TODAY , 'YYYYMMDD')...
And in this case when i try pass $DATE_TODAY into function TO_TIMESTAMP i get error:
AND o.creation_date > TO_TIMESTAMP( 20220610 , 'YYYYMMDD') error in line 30:
ORA-00932 inconsistent datatypes Expected -, NUMBER obtained
I need to pass date in single quotes like '20220610', Is it possible to do this?

You should put single quotes in the script, there is no need to escape them. Just do:
AND o.creation_date > TO_TIMESTAMP( '$DATE_TODAY' , 'YYYYMMDD')

Related

How to convert a date to a string

I want yo get only the 'date hours:minutes:seconds' from the Date column
Date
10/11/22 12:14:01,807000000
11/12/22 13:15:46,650000000
29/12/22 14:30:46,501000000
and I want to get a string column with date hours:minutes:seconds
Date_string
10/11/22 12:14:01
11/12/22 13:15:46
29/12/22 14:30:46
I tried this code but it doesn't work:
select*, TO_CHAR(extract(hour from (Date)))||':'||TO_CHAR(extract(minute from (Date)))||':'||TO_CHAR(extract(second from (Date))) as Date_string
from table;
If this is a date column, you could use to_char directly:
SELECT m.*, TO_CHAR(my_date_column, 'dd/mm/yy hh24:mi:ss')
FROM mytable m
You can use REGEX SUBSTRING function to get the date string on the left.
SELECT REGEXP_SUBSTR (Date_string, '[^,]+', 1, 1)
AS left_part
FROM Table1;
where ^, means look for chars that are NOT comma on 1st position
and get the first occurrence (on the left)
Result:
LEFT_PART
10/11/22 12:14:01
11/12/22 13:15:46
29/12/22 14:30:46
reference:
https://docs.oracle.com/cd/B12037_01/server.101/b10759/functions116.htm
Just do it with the TO_DATE() and TO_CHAR() function pair, both operating on the Oracle date format strings:
Building the scenario:
-- your input ..
WITH indata(dt) AS (
SELECT '10/11/22 12:14:01,807000000' FROM dual UNION ALL
SELECT '11/12/22 13:15:46,650000000' FROM dual UNION ALL
SELECT '29/12/22 14:30:46,501000000' FROM dual
)
-- end of your input. Real query starts here.
-- Change following comma to "WITH" ..
,
-- Now convert to TIMESTAMP(9) ...
as_ts AS (
SELECT
TO_TIMESTAMP(dt ,'DD/MM/YY HH24:MI:SS,FF9') AS ts
FROM indata
)
SELECT
ts
, CAST(ts AS TIMESTAMP(0)) AS recast -- note: this is rounded
, TO_CHAR(ts,'DD/MM/YY HH24:MI:SS') AS reformatted -- this is truncated
FROM as_ts
Result:
TS
RECAST
REFORMATTED
10-NOV-22 12.14.01.807000000
10-NOV-22 12.14.02
10/11/22 12:14:01
11-DEC-22 13.15.46.650000000
11-DEC-22 13.15.47
11/12/22 13:15:46
29-DEC-22 14.30.46.501000000
29-DEC-22 14.30.47
29/12/22 14:30:46
Going by what you have in your question, it appears that the data in the field Date is a timestamp. This isn't a problem, but the names of the table (TABLE) and field (Date) present some challenges.
In Oracle, TABLE is a reserved word - so to use it as the name of a table it must be quoted by putting it inside double-quotes, as "TABLE". Similarly, Date is a mixed-case identifier and must likewise be quoted (e.g. "Date") every time it's used.
Given the above your query becomes:
SELECT TO_CHAR("Date", 'DD/MM/YY HH24:MI:SS') AS FORMATTED_DATE
FROM "TABLE"
and produces the desired results. db<>fiddle here
Generally, it's best in Oracle to avoid using reserved words as identifiers, and to allow the database to convert all names to upper case - if you do that you don't have to quote the names, and you can refer to them by upper or lower case as the database automatically converts all unquoted names to upper case internally.

PL/SQL - to_char within DECODE

I have a DECODE statement that works fine without putting to_char function in
Select DECODE(info.make_date, NULL,'SELECT ALL',info.make_date) as "listItemKey"
However I need info.make_date to be in a specific date format, so I use to_char
Select DECODE(info.make_date, NULL,'SELECT ALL',to_char(info.make_date, 'MM/DD/YYYY')) as "listItemKey"
But when I do this I get Unexpected '<' as my JSON instead of the data I need to return. Is there a reason I can't set my info.make_date to the format I need here?
I guess an alternative could be as below. Please try and let me know if this works.
select case when info.make_date is null then 'SELECT ALL'
else TO_CHAR (info.make_date, 'MM/DD/YYYY')
end as "listItemKey"
However i would say to cast the date before using to_char with existing DECODE:
TO_CHAR (to_date(info.make_date, 'MM/DD/YYYY'), 'MM/DD/YYYY' )

Oracle sql - convert string to date

i am having problems with converting a varchar(yyyymmdd) to date(yyyymmdd).
i have a procedure with a parameter (pdate varchar2, yyyymmdd format) which needed to be converted to date type in yyyymmdd format as well.
so far i tried.
vdate date;
vdate := (to_date(SUBSTR(pdate,1,4)+SUBSTR(pdate,5,2)+SUBSTR(pdate,7,2), 'yyyymmdd'));
this threw a error of ORA-01840: input value not long enough for date format.
any help would be appreciated.
Just use a to_date
select to_date(MyDate, 'yyyymmdd')
from mytable
Test with:
select to_date('20170831','yyyymmdd')
from dual
Also, to concatenate in Oracle, use a double pipe ||
select 'Chicken'||'Food'
from dual
If pdate has other characters after yyyymmdd, and yyyymmdd is in the beginning of the whole text, you can just use
SELECT TO_DATE(SUBSTR(pdate,1,8), 'yyyymmdd')
FROM yourtable;
Example
SELECT TO_DATE(SUBSTR('20170831 10:30am',1,8), 'yyyymmdd')
FROM dual;
Otherwise, you can directly use TO_DATE() as suggested by most that replied

SQL query not returning data

I am trying to retrieve data from a Intersystems Cached database using a where clause with a timestamp, but nothing works.
Query:
select *
from dbo.iSkillsetStat
where Timestamp >= '2014-07-29 00:00:00'
Error:
ERROR: [SQLCODE: <-4>:<A term expected, beginning with one of
the following: identifier, constant, aggregate, %ALPHAUP, %EXACT,
%MVR, %SQLSTRING, %SQLUPPER, %STRING, %UPPER, $$, :,
+, -, (, NOT, EXISTS, or FOR>]
[Location: <Prepare>]
If I run the query without the timestamp all the data is returned.
Please any suggestions!
as TIMESTAMP is a reserved word, you should enclose it in double quotes "TIMESTAP"
In similar cases this worked for me:
select * from dbo.iSkillsetStat where Timestamp >= '2014-07-29T00:00:00'
Note the 'T' between the date and time values.
Try this:
select *
from dbo.iSkillsetStat
where Timestamp >= Convert(datetime, '2014-07-29 00:00:00')
Here you are missing 000 in your datetime 2014-07-29 00:00:00.
It should be like this 2014-07-29 00:00:00:000
instead of 2014-07-29 00:00:00
the field timestamp may be a reserved keyword and shouldn't be used for columnnames (have a look at https://www.drupal.org/node/141051 #728)
HINT:
if you field is of type TIMESTAMP convert the value before you compare it:
SELECT *
FROM dbo.iSkillsetStat
WHERE columnname >= TIMESTAMP('2014-07-29 00:00:00')

PLSQL - Store a select query result in variable throw error

I want to store a select query result in a variable in PLSQL.
SQL>var v_storedate VARCHAR2(19);
SQL>exec :v_storedate := 'select cdate from rprt where cdate between cdate AND TO_CHAR(sysdate, 'YYYY/MM/DD-HH24-MI-SS-SSSSS') and ryg='R' and cnum='C002'';
As
SQL>select cdate from rprt where cdate between cdate AND TO_CHAR(sysdate, 'YYYY/MM/DD-HH24-MI-SS-SSSSS') and ryg='R' and cnum='C002';
Returns : 2013/04/27-10:06:26:794
But it throws error:
ERROR at line 1: ORA-06550: line 1, column 121: PLS-00103: Encountered
the symbol "YYYY" when expecting one of the following:
* & = - + ; < / > at in is mod remainder not rem <an exponent (**)> <> or != or ~= >= <= <> and or like LIKE2_ LIKE4_ LIKEC_ between ||
multiset member SUBMULTISET_ The symbol "*" was substituted for "YYYY"
to continue. ORA-06550: line 1, column 148: PLS-00103: Encountered the
symbol ") and ryg=" when expecting one of the following: . ( * # % & =
- + ; < / > at in is mod remainder not rem <an exponent (**)> <> or != or ~= >= <= <> and or like LIKE2_ LIKE4_ LIKEC_ between
If you want to store the result of the query then you need to use a select ... into; at the moment you're trying to store the text of the actual query, not its result. If you wanted to do that you would need to escape the single-quote characters as the other answers have pointed out, and increase the variable size.
var v_storedate VARCHAR2(19);
exec select cdate into :v_storedate from rprt where cdate between cdate AND TO_CHAR(sysdate, 'YYYY/MM/DD-HH24-MI-SS-SSSSS') and ryg='R' and cnum='C002';
print v_storedate
Which would be easier to deal with using a normal anonymous block rather than SQL*Plus' execute shorthand. You should also give an explicit date format mask when converting it to a string:
begin
select to_char(cdate, 'YYYY/MM/DD-HH24:MI:SS')
into :v_storedate
from rprt
where cdate between cdate AND TO_CHAR(sysdate, 'YYYY/MM/DD-HH24-MI-SS-SSSSS')
and ryg='R' and cnum='C002';
end;
/
If you want the fractional seconds then you need to make your variable bigger, as 19 chars will only take you to the seconds.
Either way though you're risking getting either multiple results (which will give ORA-02112) or no results (which will give ORA-01403). As your where clause doesn't make much sense and the table contents aren't known I don't know which is more likely. As be here now pointed out your cdate comparison is always going to be true, plus you're doing an implicit date conversion in there which will break at some point. There isn't enough information to fix that for you.
You can't get fractional seconds from a date value anyway, only from a timestamp; which cdate seems to be. But even then the format element for that is FF[0-9]. SSSSSS is the number of seconds since midnight. But as the whole to_char() bit looks wrong that's somewhat moot. Also, if you really do need a comparison with the current time, you should probably be comparing with systimestamp rather than sysdate to be consistent - and then not doing any conversion of that.
If you only want the date part:
var v_storedate VARCHAR2(10);
begin
select to_char(cdate, 'YYYY/MM/DD')
into :v_storedate
...
You can still use exec if you want to, but it's less readable once the statement gets longer than your terminal line length:
var v_storedate VARCHAR2(10);
exec select to_char(cdate, 'YYYY/MM/DD') into :v_storedate from ... where ... ;
In PL/SQL a better approach to literals with single quotes in them is the quotation syntax: http://docs.oracle.com/cd/B28359_01/appdev.111/b28370/fundamentals.htm#CBJJDDCG
begin
variable := q'#select cdate from rprt where cdate between cdate AND TO_CHAR(sysdate, 'YYYY/MM/DD-HH24-MI-SS-SSSSS') and ryg='R' and cnum='C002'#'
...
end
... or with matching delimiters ...
begin
variable := q'[select cdate from rprt where cdate between cdate AND TO_CHAR(sysdate, 'YYYY/MM/DD-HH24-MI-SS-SSSSS') and ryg='R' and cnum='C002']'
...
end
You might try that in SQL*Plus also ... not sure if it works there.
Escape your inner apostrophes by doubling them!
Double the inner apostrophes.
And Change Data Type of v_storedate to VARCHAR2(140);