Query Oracle DB for timestamps when you know milliseconds - database

I'm currently getting the error:
java.sql.SQLException: ORA-01843: not a valid month
which I assume is to do with the way I am setting a timestamp...
So I have a query like this :
select * from A_TABLE where A_TIMESTAMP_COL < '1252944840000'
But it doesn't work...and I don't want to have to convert it to a date ideally. Is there some special syntax to tell Oracle that this is a timestamp?

You can use the to_timestamp() function to convert your string into a timestamp value: http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/functions201.htm#sthref2458

I think you can cast the date column to a char and do something like:
select * from A_TABLE where to_char(A_TIMESTAMP_COL) < '1252944840000'
This should allow you to compare strings, not dates.

Use the java.sql convenience methods to take that milisecond time and turn it into a Date or Timestamp.

You can use this query:
SELECT * FROM A_TABLE WHERE TIMESTAMP < (SYSDATE - 10/1440)
Where (SYSDATE - 10/1440) means SYSDATE - 10 Minutes.
Also see some examples here.

Related

How I can Get Records of Specific date in Microsoft Access Database like 10/21/2018 dd/mm/yyyy?

Here is Code of My Query Search in MS-ACCESS (.MDB),
I am trying this
Select * from Records where date like '10/21/2018%'
It will be:
select * from Records where [date] = #10/21/2018#
Addendum:
One method to ignore a time part of the date field:
select * from Records where Fix([date]) = #10/21/2018#
Following Query Solve my issue, Thanks #ashleedawg and #Gustav for your suggestions.
SELECT * FROM TABLE WHERE DATE > #10/20/2018# AND DATE < #10/22/2018#
If your date column is of datatype datetime, using the like operator will convert your datetime to text which depends on regional settings. Also, the placeholder for "any string" in Access is *, not %. Assuming that you used that placeholder to ignore the time, you better try something like this:
Select * from Records where DateValue([date]) = #10/21/2018#

SQL Server date formatting issue

I have a SQL Server 2008 database with a transaction table. There is a field defined as NVARCHAR(16). The data stored is date and time formatted like this:
2016100708593100
I need to write a query that looks at that field and pulls data between two dates
select ... from...where convert(varchar,
convert(datetime,left(a.xact_dati,8)),101)
between '9/29/2016' and '10/05/2016'
I have tried other converts but nothing returns any data. If I use >=getdate()-1
I get data so I should be seeing something returned. Any suggestions?
Replace WHERE Clause with
... WHERE CONVERT(DATETIME,LEFT(a.xact_dati,8)) BETWEEN '9/29/2016' AND '10/05/2016'
Assuming YMD order just
where cast(left('2016100708593100', 8) as date) between '20160929' and '20161005'
Note this clause is not satisfied.
The problem is you're trying to do a date comparison with varchar data.
You go half way to converting the initial value to datetime but then back to varchar.
You could rely on Sql to implicitly convert the between parameters to datetime.
select 'matched',convert(datetime,left('2016100708593100',8),112)
where convert(datetime,left('2016100708593100',8),112) between '2016/09/29' and '2016/10/10'
Take the date part of the string and CAST it as DATE and then compare it with the proper date format.
select ... from...
where cast(left('2016100708593100', 8) as date) between '2016-09-29' and '2016-10-10'
a very straight and fast approach could be to keep this in BIGINT
Something like this:
cast(left(a.xact_dati,8) as bigint) between 20160929 and 20161005
But anyway this will not be sargable and therefore cannot use an index.
You might even stick to varchar, as the YYYYMMDD format is safe with alphanumerical sorting. Cutting a string with LEFT is sargable (AFAIK):
left(a.xact_dati,8) between '20160929' and '20161005'

USING DATEADD IN DERIVED COLUMN TRANSFORMATION IN SSIS

I am trying to use DATEADD function in a derived column transformation but it seems the expression i am using is wrong. Initially, i was using this in my SQL query which works fine but i want to use it now in a derived column so i can transform the date value before i bring it into my table. Here is the sql i was using:
select DATEADD(day,myDate,'19600101') as NewDate from myTable
but i want to use it now in derived column so i am replacing the column and using this in the expression:
DATEADD("day", myDate, "19600101" )
I just had the same problem, here is the fix:
instead of:
DATEADD("day", myDate, "19600101" )
try:
DATEADD("day", (DT_DBDATE)myDate, (DT_DBDATE)"19600101")
This will return a database datestamp, which can be cast back to a string if needed. In my case, I am converting from Epoch time (milliseconds since 1/1/1970), so I need this:
DATEADD("s",(DT_I8)[Index Time],(DT_DBTIME)"1/1/1970")
Please see the documentation for dateadd: http://msdn.microsoft.com/en-us/library/ms141719.aspx. I am not sure what you are tryinmg to do with this expression. If you wanted to add one day then it would be:
select DATEADD(d,1,myDate) as NewDate from myTable
If you wanted to subtract one day then it would be:
select DATEADD(d,-1,myDate) as NewDate from myTable
Please explain what you are trying to do. I do not think the first arguement should be inside double quotes. Also "day" is not allowed according to the remarks section in my link.

How to convert SQL Server's timestamp column to datetime format

As SQL Server returns timestamp like 'Nov 14 2011 03:12:12:947PM', is there some easy way to convert string to date format like 'Y-m-d H:i:s'.
So far I use
date('Y-m-d H:i:s',strtotime('Nov 14 2011 03:12:12:947PM'))
SQL Server's TIMESTAMP datatype has nothing to do with a date and time!
It's just a hexadecimal representation of a consecutive 8 byte integer - it's only good for making sure a row hasn't change since it's been read.
You can read off the hexadecimal integer or if you want a BIGINT. As an example:
SELECT CAST (0x0000000017E30D64 AS BIGINT)
The result is
400756068
In newer versions of SQL Server, it's being called RowVersion - since that's really what it is. See the MSDN docs on ROWVERSION:
Is a data type that exposes automatically generated, unique binary numbers within a database. rowversion is generally used as a mechanism
for version-stamping table rows. The
rowversion data type is just an incrementing number and does not
preserve a date or a time. To record a date or time, use a datetime2
data type.
So you cannot convert a SQL Server TIMESTAMP to a date/time - it's just not a date/time.
But if you're saying timestamp but really you mean a DATETIME column - then you can use any of those valid date formats described in the CAST and CONVERT topic in the MSDN help. Those are defined and supported "out of the box" by SQL Server. Anything else is not supported, e.g. you have to do a lot of manual casting and concatenating (not recommended).
The format you're looking for looks a bit like the ODBC canonical (style = 121):
DECLARE #today DATETIME = SYSDATETIME()
SELECT CONVERT(VARCHAR(50), #today, 121)
gives:
2011-11-14 10:29:00.470
SQL Server 2012 will finally have a FORMAT function to do custom formatting......
The simplest way of doing this is:
SELECT id,name,FROM_UNIXTIME(registration_date) FROM `tbl_registration`;
This gives the date column atleast in a readable format.
Further if you want to change te format click here.
Using cast you can get date from a timestamp field:
SELECT CAST(timestamp_field AS DATE) FROM tbl_name
Works fine, except this message:
Implicit conversion from data type varchar to timestamp is not allowed. Use the CONVERT function to run this query
So yes, TIMESTAMP (RowVersion) is NOT a DATE :)
To be honest, I fidddled around quite some time myself to find a way to convert it to a date.
Best way is to convert it to INT and compare. That's what this type is meant to be.
If you want a date - just add a Datetime column and live happily ever after :)
cheers mac
My coworkers helped me with this:
select CONVERT(VARCHAR(10), <tms_column>, 112), count(*)
from table where <tms_column> > '2012-09-10'
group by CONVERT(VARCHAR(10), <tms_column>, 112);
or
select CONVERT(DATE, <tms_column>, 112), count(*)
from table where <tms_column> > '2012-09-10'
group by CONVERT(DATE, <tms_column>, 112);
"You keep using that word. I do not think it means what you think it means."
— Inigo Montoya
The timestamp has absolutely no relationship to time as marc_s originally said.
declare #Test table (
TestId int identity(1,1) primary key clustered
,Ts timestamp
,CurrentDt datetime default getdate()
,Something varchar(max)
)
insert into #Test (Something)
select name from sys.tables
waitfor delay '00:00:10'
insert into #Test (Something)
select name from sys.tables
select * from #Test
Notice in the output that Ts (hex) increments by one for each record, but the actual time has a gap of 10 seconds. If it were related to time then there would be a gap in the timestamp to correspond with the difference in the time.
for me works:
TO_DATE('19700101', 'yyyymmdd') + (TIME / 24 / 60 / 60)
(oracle DB)
Robert Mauro has the correct comment. For those who know the Sybase origins, datetime was really two separate integers, one for date, one for time, so timestamp aka rowversion could just be considered the raw value captured from the server. Much faster.
After impelemtation of conversion to integer
CONVERT(BIGINT, [timestamp]) as Timestamp
I've got the result like
446701117
446701118
446701119
446701120
446701121
446701122
446701123
446701124
446701125
446701126
Yes, this is not a date and time, It's serial numbers
Why not try FROM_UNIXTIME(unix_timestamp, format)?
I had the same problem with timestamp eg:'29-JUL-20 04.46.42.000000000 PM'. I wanted to turn it into 'yyyy-MM-dd' format. The solution that finally works for me is
SELECT TO_CHAR(mytimestamp, 'YYYY-MM-DD') FROM mytable;
I will assume that you've done a data dump as insert statements, and you (or whoever Googles this) are attempting to figure out the date and time, or translate it for use elsewhere (eg: to convert to MySQL inserts). This is actually easy in any programming language.
Let's work with this:
CAST(0x0000A61300B1F1EB AS DateTime)
This Hex representation is actually two separate data elements... Date and Time. The first four bytes are date, the second four bytes are time.
The date is 0x0000A613
The time is 0x00B1F1EB
Convert both of the segments to integers using the programming language of your choice (it's a direct hex to integer conversion, which is supported in every modern programming language, so, I will not waste space with code that may or may not be the programming language you're working in).
The date of 0x0000A613 becomes 42515
The time of 0x00B1F1EB becomes 11661803
Now, what to do with those integers:
Date
Date is since 01/01/1900, and is represented as days. So, add 42,515 days to 01/01/1900, and your result is 05/27/2016.
Time
Time is a little more complex. Take that INT and do the following to get your time in microseconds since midnight (pseudocode):
TimeINT=Hex2Int(HexTime)
MicrosecondsTime = TimeINT*10000/3
From there, use your language's favorite function calls to translate microseconds (38872676666.7 µs in the example above) into time.
The result would be 10:47:52.677
Some of them actually does covert to a date-time from SQL Server 2008 onwards.
Try the following SQL query and you will see for yourself:
SELECT CAST (0x00009CEF00A25634 AS datetime)
The above will result in 2009-12-30 09:51:03:000 but I have encountered ones that actually don't map to a date-time.
Not sure if I'm missing something here but can't you just convert the timestamp like this:
CONVERT(VARCHAR,CAST(ZEIT AS DATETIME), 110)

C, unixODBC, oracle and Date queries

I've got a query like
select x from tableName where startDate <= now;
When i query the database without the date fields, everything works as expected. As soon as i start using date or timestamp columns in the oracle Database, my queries return nothing or an error.
What I do:
snprintf(sql, sizeof(sql), "SELECT roomNo, userPass, adminPass, adminFlags, userFlags, bookId, is_locked, running_on_server FROM booking WHERE roomNo = '?' AND startTime <= { ts '?' } AND endTime >= { ts '?' } for update;");
stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
the ? will be replaced by values, with following command:
SQLBindParameter(stmt, i + 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(gps->argv[i]), 0, gps->argv[i], 0, NULL);
when I execute the query I get an error that TS is an invalid identifier [this was a recommendation by another board, taken from msdn - which may cause this error]
but even if I remove it and send just a string to the database, I'll get an empty result back. I also tried to bind the parameters as SQL_TIMESTAMP and SQL_DATE, but this didn't help either.
Hopefully somebody can help me.
thanks in advance.
Chris
Are you sending a DATE data type to the Oracle query or a date represented in a string?
From the Oracle side of things, if you send a date in a string variable you'll need to use the oracle "TO_DATE" function (http://www.techonthenet.com/oracle/functions/to_date.php) to then convert thew string back to a date for use in your SQL statement (assuming startDate or startTime/endTime are DATE columns in the database).
Your fist SQL example should be:
SELECT x
FROM tableName
WHERE startDate <= TO_DATE(now, '<date-format>');
If the variable "now" was a string containing '05-OCT-2011 16:15:23' (including a time portion) then the to_date would be:
TO_DATE(now, 'DD-MON-YYYY HH24:MI:SS')
If you compare a string with a date and don't specify the format of that date Oracle will use its default NLS parameters and try to apply that format. Therefore it is always prudent to specify the date format using TO_DATE.
Hope it helps...

Resources