Select a datetime in Tsql, trim the milliseconds and return as a string - tsql

Problem: I want to select a date (stored as datetime) and return is as a string with the milliseconds trimmed off.
eg 2017-01-04 08:47:30.0000000 => "2017-01-04 08:47:30"
My current solutions:
I have got 3 statements which do the above:
Substring option
select
SUBSTRING(CONVERT(nvarchar,EventDate),0,20)
from EventsTable
Double convertions
select
CONVERT(nvarchar, CONVERT(datetime2(0),EventDate))
from EventsTable
Short nvarchar
select
CONVERT(nvarchar(19),EventDate)
from EventsTable
Allof the above solutions work and achieve my goal.
Question:
What is the best practice / most efficient way to achieve my goal?

Use a date style in your convert:
select CONVERT(varchar(19),EventDate,120)
from EventsTable
I would use this. It uses only one function, and sets the correct length for the varchar, and the format tells SQL Server the correct format you need.
Since style 120 is a standard you are sure that it the same no matter what localisation settings are on your DB or Session.

I ran all the three queries with the Execution Plan enabled with SQL Server 2008R2.
I received the cost equal in all of them ( 33% each).
All the three queries take the same time and resources.
However, the third one might help you with the less code being written.

Related

Convert varchar data to time format in postgresql

I currently have a range of transaction data, and I am trying to query the data for the sum of transactions within a certain time frame. One field, transaction_time is a varchar. An example of one of these times is "13:42", which corresponds to 1:42pm. I was experimenting around with to_timestamp, but I have been unable to figure it out. Would anyone have any idea as to how to alter this varchar to represent time data.
Kind regards
Casting can be done two ways:
select cast('12:47' as time)
and
select '12:47'::time
cast it to time.
select cast('13:42' as time)

Postgres timestamp to date

I am building a map in CartoDB which uses Postgres. I'm simply trying to display my dates as: 10-16-2014 but, haven't been able to because Postgres includes an unneeded timestamp in every date column.
Should I alter the column to remove the timestamp or, is it simply a matter of a (correct) SELECT query? I can SELECT records from a date range no problem with:
SELECT * FROM mytable
WHERE myTableDate >= '2014-01-01' AND myTableDate < '2014-12-31'
However, my dates appear in my CartoDB maps as: 2014-10-16T00:00:00Z and I'm just trying to get the popups on my maps to read: 10-16-2014.
Any help would be appreciated - Thank you!
You are confusing storage with display.
Store a timestamp or date, depending on whethether you need time or not.
If you want formatted output, ask the database for formatted output with to_char, e.g.
SELECT col1, col2, to_char(col3, 'DD-MM-YY'), ... FROM ...;
See the PostgreSQL manual.
There is no way to set a user-specified date output format. Dates are always output in ISO format. If PostgreSQL let you specify other formats without changing the SQL query text it'd really confuse client drivers and applications that expect the date format the protocol specifies and get something entirely different.
You have two basic options.
1 Change the column from a timestamp to a date column.
2 Cast to date in your SQL query (i.e. mytimestamp::date works).
In general if this is a presentation issue, I don't usually think that is a good reason to muck around with the database structure. That's better handled by client-side processing or casting in an SQL query. On the other hand if the issue is a semantic one, then you may want to revisit your database structure.

convert string date(yyyy/mm/dd) to date format in db2

I am saving the date as varchar in db2 with yyyy/mm/dd format i need to convert it to date datetype in the query how to achieve this?
I tried
select DATE(CRDTR2) from ASAODLIB.SSLR204 where CRDTR2 BETWEEN
'2015/03/01' AND '2015/03/31';
query and got the below error
The syntax of the string representation of a datetime value is
incorrect.. SQLCODE=-180, SQLSTATE=22007, DRIVER=3.68.61
can someone help me.
If your DB2 version is new enough, use to_date: select DATE(TO_DATE(CRDTR2, 'YYYY/MM/DD')) from ...
...because it doesn't recognize that format. I'd turn it into *ISO first, via REPLACE:
SELECT DATE(REPLACE(CRDTR2, '/', '-'))
FROM ASAODLIB.SSLR204
WHERE CRDTR2 BETWEEN '2015/03/01' AND '2015/03/31'
Incidentally, there's a couple other things here.
You should be storing dates as an actual date type, which would make this a non-issue.
You shouldn't use BETWEEN, in preference for an exclusive upper-bound (< - the blog talks about SQL Server, but the problem is really due to representation. That, and most versions of DB2 allow you to specify fractional seconds in timestamps...).

FileNet - SQL for a date property between specific hours

I would like to fetch documents that a property date hour is between midnight and 4 AM.
I tried this:
SELECT [This], [Date], FROM Folder_Type_1
WHERE DATEPART(hh,[Date]) >= 0
AND DATEPART(hh,[Date]) <= 4
ORDER BY Date
and
SELECT [This], [Date], FROM Folder_Type_1
WHERE CONVERT(VARCHAR(8),Date,108) between '00:00:00' and '04:00:00'
ORDER BY Date
But none of them is working when I test it in the SQL query builder in the FEM.
DATEPART and CONVERT are not recognised. What is the correct way to do it?
I didn't find anything interesting in this SQL syntax reference.
Thank you in advance!
You are trying to use T-SQL functions within Content Engine Query Language. While its syntax might look like SQL, it is actually not. Not to mention it is obviously not T-SQL.
As of today, it is not possible to accomplish what you want. TimeSpan function introduced in the version 5.1 allows some manipulations with date parts. Those, however, are not sufficient for your task. You might want to check TimeSpan documentation.
I have used the follwoing before:
where c.DateCreated >= 20130101T000000Z
This is a snippet from a query executed using the api an not the fem, but in principle this should be the same sql

Best method for varchar date validation in Sybase (T-SQL)?

I have a stored procedure which takes as its parameter a varchar which needs to be cast as a datetime for later use:
SET #the_date = CAST(#date_string AS DATETIME)
I'm expecting the date string to be supplied in the format "DD-MON-YYYY", but in an effort to code defensively, if for some reason it can't be cast successfully, I want to default to the system date and continue. In PL/SQL I could use exception handling to achieve this and I could do this fairly easily with regular expressions too, but the limited pattern matching supported out of the box by Sybase doesn't let me do this and I can't rely on third party libraries or extensions. Is there a simple way of doing this in T-SQL?
NB: using Sybase ASE 12.5.3, there is no ISDATE function
I'm having a similar issue. You might be able to do something like this:
SET arithabort arith_overflow off
SET #the_date = CAST(#date_string AS DATETIME)
IF #the_date is NULL
set #the_date = getdate()
SET arithabort arith_overflow on
However, this doesn't work well in a select. It will work well in a cursor (boo) or in logic before / after a SQL batch.
My goodness, if the question was about Microsoft SQL Server then we'd have been in business!
Sybase, sadly, is a whole 'nother database these days, since about 1997, in fact, give or take a year.
If the input format simply has to be 'DD-MON-YYYY' and no exceptions, then I think a fair amount of validation was be achieved by slicing the input using SUBSTR(), after first doing some simple things, such as checking length.
I thought that recent releases of Sybase (SQL Anywhere 11, for example) have regular expression support, however, although it's been a while since I've had to suffer T-SQL. Some googling leaves me in rather more doubt.
Can't you do something like this:
SELECT #the_date = CASE #date_string
WHEN '[0-9][0-9]-[A-Z][A-Z][A-Z]-[0-9][0-9][0-9][0-9]'
THEN CONVERT(datetime, #date_string)
ELSE GETDATE()
END
?
Found this in the second result in Google when searching for "validate date string sql".
----Invalid date
SELECT ISDATE('30/2/2007')
RETURNS : 0 (Zero)
----Valid date
SELECT ISDATE('12/12/20007')
RETURNS : 1 (ONE)
----Invalid DataType
SELECT ISDATE('SQL')
RETURNS : 0 (Zero)
Make sure SQL Server knows the order of Days, Months and Years in your string by executing
SET DATEFORMAT mdy;
Did you try convert instead of cast?
select convert( datetime , #date_string )