How do I strip the date off of a datetime string in SQL SSIS? - sql

I'm working on a data warehouse project and would like to know how to (preferably in a Derived Column component in a Data flow) strip the date piece off of a SQL datetime record.
Once I have the datetime converted to just a time I am going to do a lookup on the time to find the related time record in a time dimension table.
Can someone give me a simple function to accomplish this inside a derived column transform?
Example: Transform a datetime such as "12/02/2008 11:32:21 AM" into simply "11:32:21 AM".

I would just do a cast to DT_DBTIME type (using Derived Column transform, or Convert type transform). DT_DBTIME contains just (hours, minutes, seconds) part of the date/time, so you'll get rid of the date part.

If you need to do this in a variable expression Michael's solution won't work, but you can use the following expression:
(DT_DATE)(DT_DBDATE)GETDATE()
(DT_DBDATE) converts the current date and time to a date only. But the new datatype is not compatiple with SSIS's datetime. Therefore you'll have to use (DT_DATE) for converting to a compatible type.
Courtesy of this solution belongs to Russel Loski who has posted it in his blog:
http://www.bidn.com/blogs/RussLoski/ssas/1458/converting-datetime-to-date-in-ssis

Actually if you reverse the first 2 expressions like this: (DT_DBDATE)(DT_DATE)GETDATE()
instead of (DT_DATE)(DT_DBDATE)GETDATE(), then you will TRUNCATE the time off the date field.
If the DT_DATE expression is before the DT_DBDATE expression, you will still have the time portion in your output, but it will be reset to all zeroes.

Ran into this with writing a report for a scheduling app, needed the time that was stored as part of a datetime data type. I formated the datetime as 0 which gives you this mon dd yyyy hh:miAM (or PM), and just did a substring of that which returned the time only in an AM/PM format.
Example below.
DECLARE #S DATETIME = GETDATE()
SELECT SUBSTRING(CONVERT(NVARCHAR(30), #S , 0) , 13 , 10) AS ApptTime
, CONVERT(NVARCHAR(30), #S , 0) AS ApptDate

I personally use a series of functions for this. E.g.:
ALTER FUNCTION [dbo].[TIMEVALUE]
(
#Datetime datetime
)
RETURNS datetime
AS
BEGIN
RETURN (#Datetime - CAST(ROUND(CAST(#Datetime AS float), 0, 1) AS datetime))
END
I'd love to claim all the credit but it should really go to this guy.

Related

SQL How to format M/DD/YYYY (1/31/1960) to DD/MM/YYYY (31/01/1969)

I have a column that has date and time mixed together i.e. 1/31/1960 12:00:00AM and I would like to convert them into two-column through SQL function:
(a) DD/MM/YYYY i.e 31/01/1969
(b) HH:MM i.e 12:00
Thanks in advance.
Take a look at the CONVERT() function, specifically the style for datetime. Additionally, we can CAST() the DATETIME as a TIME data type to extract the time.
Assuming your original column is a DATETIME data type, you can run
SELECT
CONVERT(NVARCHAR(24),{DateField},103)
,CAST({DateField} AS TIME)
If it is string, you can cast it then convert
SELECT
CONVERT(NVARCHAR(24),CAST('1960-01-31' AS DATETIME),103) AS ReportingDate
,CAST(CAST('1960-01-31' AS DATETIME) AS TIME) AS ReportingTime
If you're on a sufficiently recent version of SQL Server, the FORMAT() function is your friend.
DECLARE #d DATE = GETDATE();
SELECT FORMAT(#d, 'dd/MM/yyyy');
Note, that second argument is a .NET formatting string, so you should be able to use whatever is available from the Framework.

How do I convert a value after using DATEADD with it

I have a little query that strips the date from the datetime field but when I try to convert it from GMT to CST it readds the date. Is there a better way to do this?
Location table:
arrival
4-6-2018 12:35:43
SELECT arrival
FROM(
SELECT CONVERT(VARCHAR(8), arrival))
FROM locations
)a
This query will give me this result:
12:35:43
SELECT (DATEADD(hour,-5,arrival))
FROM(
SELECT CONVERT(VARCHAR(8), arrival))
FROM locations
)a
4-6-2018 12:35:43
This query will give readd the date. How can I remove the date and then do the dateadd function without it readding the date
arrival seems to be a DateTime, which always carries a date part. You need a time instead, supported by SQL Server 2008+:
cast(DATEADD(hour,-5,arrival) as time)
To quote from DATEADD (Transact-SQL) - Return Types:
The return data type is the data type of the date argument, except for string literals. The return data type for a string literal is datetime. An error will be raised if the string literal seconds scale is more than three positions (.nnn) or contains the time zone offset part.
Emphasis my own.
As you are passing a string (varchar), then DATEADD is returning a datetime.
Like those in the comments have said, if you use the correct data type (time) this problem goes away:
SELECT DATEADD(HOUR, -5,CONVERT(time,Arrival))
FROM (VALUES('4-6-2018 12:35:43'),('4-6-2018 07:35:43'),('4-6-2018 03:35:43')) V(Arrival)
Probably this is what you are asking for:
SELECT Convert(Varchar(8), DATEADD(hour,-5,arrival), 108)
FROM locations;
Note: This is compatible with SQL server versions that doesn't have Time datatype too.

varchar vs datetime in sql

I was having problem in retrieving from SQL Server so I posted this [question][1]
I did not get any suitable answers. So I have changed the column datatype from datetime to varchar and now it works fine.
SELECT *
FROM test
WHERE (timeStamp BETWEEN '05-09-2013 18:23:57' AND '05-09-2013 18:23:59')
But my query if varchar datatype can play the role of datetime and in varchar we can also store the string then why sql provides datetime datatype? I know varchar occupies more space than datetime. I would like to know other reasons.
Change datatype of your column to datetime. You can do your query IF you'll use datetime instead of varchar in where clause:
select *
from test
where timeStamp between convert(datetime, '2013-09-05 18:23:57', 120) and convert(datetime, '2013-09-05 18:23:59', 120)
I'm pretty sure it would work even with implicit cast if you use ISO format of date:
select *
from test
where timeStamp between '2013-09-05 18:23:57' and '2013-09-05 18:23:59'
Here's more info about cast and convert.
Another reason apart from space is this:
Datetime has other functions like picking up the day, year, month,hours,minutes,seconds etc so that you don't have to write it for yourself. If you use varchar then it will be your responsibility to provide functions for future use. You should use split function to retrive the part of date you want.
Another is that a query on a varchar works slower when compared to Datetime when you use to conditions to compare month / day/ year
Always use proper DATETIME datatype to store date and time values. Refer this for more information
http://beyondrelational.com/modules/2/blogs/70/posts/10902/understanding-datetime-column-part-iv.aspx

How can I convert a varchar field (YYYYMM) to a date (MM/01/YY) in SQL?

I'm sure this is quite simple, but I've been stuck on it for some time. How can I convert a varchar field (YYYYMM) to a date (MM/01/YY) in SQL?
Thanks.
Edit: I'm using Open Office Base (HSQL), not MySQL; sorry for the confusion.
Try the str_to_date and date_format functions. Something like:
select date_format( str_to_date( my_column, '%Y%c' ), '%c/01/%y' ) from my_table
try :
SELECT STR_TO_DATE(CONCAT(myDate,'01'),'%Y%m%d')
FROM myTable
Use STR_TO_DATE:
From mysql.com:
STR_TO_DATE(str,format)
This is the inverse of the DATE_FORMAT() function. It takes a string str and a format string format. STR_TO_DATE() returns a DATETIME value if the format string contains both date and time parts, or a DATE or TIME value if the string contains only date or time parts.
The date, time, or datetime values contained in str should be given in the format indicated by format. For the specifiers that can be used in format, see the DATE_FORMAT() function description. If str contains an illegal date, time, or datetime value, STR_TO_DATE() returns NULL. Starting from MySQL 5.0.3, an illegal value also produces a warning.
Range checking on the parts of date values is as described in Section 11.3.1, “The DATETIME, DATE, and TIMESTAMP Types”. This means, for example, that “zero” dates or dates with part values of 0 are allowed unless the SQL mode is set to disallow such values.
mysql> SELECT STR_TO_DATE('00/00/0000', '%m/%d/%Y');
-> '0000-00-00'
mysql> SELECT STR_TO_DATE('04/31/2004', '%m/%d/%Y');
-> '2004-04-31'
Get the year:
SUBSTRING(field FROM 2 FOR 2)
Get the month:
SUBSTRING(field FROM -2 FOR 2)
Compose the date:
CONCAT(SUBSTRING(field FROM -2 FOR 2), '/01/', SUBSTRING(field FROM 2 FOR 2))
This will convert from YYYYMM to MM/01/YY.
To be clear: if you're looking for method to convert some value of type Varchar/Text to value of type Date than solutions are:
using CAST function
CAST(LEFT('201205',4)||'-'||SUBSTRING('201205' FROM 5 FOR 6)||'-01' AS DATE)
starting from OpenOffice 3.4 (HSQLDB 2.x) new Oracle-like function TO_DATE supposed to be available
TO_DATE('201205','YYYYMM')
in addition to the written i can mention that you also can construct a string with ANSI/ISO 'YYYY-MM-DD' formatted representation of the date,- Base will acknowledge that and succesfully convert it to the Date type if necessary (e.g. INSERTing in Date typed column etc.)
Here is doc's on HyperSQL and highly recommended OO Base guide by Andrew Pitonyak

how to convert nvarchar to time ,not datetime?

DECLARE #DateNow smalldatetime
SET #DateNow='12:30'
select #DateNow
-------------------------------------OR--------------------------------------
select CAST( '12:30' as datetime )
Result: 1900-01-01 12:30:00.000 (i don't want this)
But i need this result in time format not string not datetime?
Result: 12:30 (i want this)
Like José said, you can use CONVERT to display a datetime as date. MSDN has a list of all possible formats. For example format 8 is hh:mi:ss:
select convert(varchar(32),getdate(),8)
12:51:21
Now, you can cut the seconds off by specifying less characters:
select convert(varchar(5),getdate(),8)
12:51
Another often used format is 121, yyyy-mm-dd hh:mi:ss.mmm(24h):
select convert(varchar(32),getdate(),121)
2009-05-08 12:51:21.987
Where you can pick the time part like:
select substring(convert(varchar(32),getdate(),121),12,5)
12:51
Or to combine the string trickeries:
select right(convert(varchar(16),getdate(),121),5)
12:51
Right? Right!
There's a TIME type in SQL Server 2008, but in previous versions, you can represent it as a varchar for display.
This is how you can retrieve the time portion of a DATETIME field in the format you want.
DECLARE #DateNow smalldatetime
SET #DateNow = GETDATE() -- 2009-05-08 12:58:02.680
SELECT CONVERT(CHAR(5), #DateNow, 8)
-- this returns the time portion as 12:58
You can use the CONVERT function.
By the way, there's no "TIME" datatype in SQL Server. So, the converted result will always be a STRING.
EDIT: There's no "TIME" datatype in SQL Server versions < SQL Server 2008.
If you need to compare, add and/or subtract time (only) values, think about the possibility to use a INT to store the "TIME" value and then to CONVERT it to CHAR when displaying the result.