How to get the date from a varchar - sql-server

I have an issue retrieving the data that I would like. I have a Varchar column that consist of various information. I would like to extract the date from that column only. However, I have been unsuccessful. I used the following SQL(2008) to get the data below, But I can't seem to just get the date only without the time. Obviously, the date and time are in different position. Hope you can help.
SELECT substring(Data, 8, 17)
from mastInfo
9/25/2013 12:36:5
Jul 8 2013 11:40
9/25/2013 12:43:5

SELECT convert(date, Case When IsDate(substring(Data, 8, 17)) = 1
Then substring(Data, 8, 17)
Else NULL END)
from mastInfo
Since you are starting off with a string, it is possible that it does not represent a valid date. Using the IsDate function will return 1 when the string can be converted to a date. Basically, this code will convert to date those values that can be converted, and will return NULL for those values that cannot be converted to a valid date.

If you are using SQL Server 2012 or newer, then you can use Try_Convert().
Here's the SQL Fiddle.
Here's an example (from the above SQLFiddle):
Select Try_Convert(datetime, DateAsString) As DateAsDateTime
,DateAsString
From SomeTable
Here's the result:
DATEASDATETIME DATEASSTRING
September, 25 2013 12:36:05+0000 9/25/2013 12:36:5
September, 25 2013 12:43:05+0000 9/25/2013 12:43:5
July, 08 2013 11:40:00+0000 Jul 8 2013 11:40

if you want convert it to date time use :
SELECT CONVERT(Datetime, '2011-09-28 18:01:00', 120) -- to convert it to Datetime
if you want get time :
SELECT LTRIM(RIGHT(CONVERT(VARCHAR(20), '2011-09-28 18:01:00', 100), 7))
if you want date part :
SELECT CONVERT (DATE, GETDATE())

what version of sql server?
can you try this:
SELECT convert(date, substring(Data, 8, 17))
from mastInfo

First convert Varchar into DateTime and after that again convert it in varchar in desired date format like 101,102,103
Try this:
select convert(varchar(50),convert(datetime,'9/25/2013 12:43:5'),101)

Related

change ID number format of number to date format

I would like to write an ID number from this format YYMMDDXXXXXXX to this 19YY-MM-DD or 20YY-MM-DD in sql.
select Customer_identifier from MartDB.DBO.BAW_AllSources_Stage1_202005
Customer_identifier cexample is 8801213535353 where 88 represents year of birth 1988, 01 represents month of birth January, 21 represents day of birth the 21st. 21 Jan 1988. I want to convert that to a date 1988-01-21
Below the script but work only with born date <2000 because you have a design problem
SELECT TRY_CAST('19'+ SUBSTRING(CAST(8801213535353 AS varchar(13)), 1, 6) AS date)
I used TRY_CAST because return a value cast to the specified data type if the cast succeeds, otherwise, returns null.
You can also format the date in a different way using FORMAT function (from SQL Server 2012).
Some example:
SELECT FORMAT(TRY_CAST('19'+ SUBSTRING(CAST(8801213535353 AS varchar(13)), 1, 6) AS date), 'yyyy-MMMM-dd')
The output is: 1988-January-21
Example with culture parameter:
SELECT FORMAT(TRY_CAST('19'+ SUBSTRING(CAST(8801213535353 AS varchar(13)), 1, 6) AS date), 'D', 'En-Us')
The output is: Thursday, January 21, 1988

Convert SQL Server date to DB2 date

Here is db2 date format
1190707 - CYYMMDD
I would like to be able to convert a SQL Server DATE to this format
I found out i can use
SELECT FORMAT(GETDATE(), 'yyMMdd')
but problem now is to get the 1st character which i have no idea what it is
The C is a century digit. And it seems to be based on the 20th century, thus years starting with 19. For years starting with 20, the century digit is one and for the 20th century the century digit is omitted.
This should do the trick
DECLARE #DateToConvert AS DATE
SELECT #DateToConvert = GETDATE()
--SELECT #DateToConvert = DATEADD(year, -100, GETDATE())
SELECT
CAST(
CONCAT(
CAST((DATEPART(YEAR, #DateToConvert)/1000) AS INT)-1,
FORMAT(#DateToConvert, 'yyMMdd')
) AS BIGINT)
I believe this works
SELECT FORMAT(GETDATE(), 'yyyyMMdd') - 19000000

SQL Server substring to date in a where caluse

I'm attempting to take a date contained within a varchar to compare it with getdate() in a where clause. The varchar variable always looks like this:
Last seen: MM/DD/YY
Some sample data:
Last Seen: 07/12/16
Last Seen: 08/01/16
Last Seen: 07/22/16
NULL
NULL
NULL
NULL
Last Seen: 07/28/16
Converting a varchar to datetime and finding the days difference as below works:
datediff(day,CAST(substring(CA_NOTE, 12, 8) as datetime), getdate()) as dayspassed
The problem is, when I stick this coding in the where clause to compare the date to getdate() I keep getting the same error.
where datediff(day,CAST(substring(CA_NOTE, 12, 8) as datetime), getdate()) > 90
Msg 241, Level 16, State 1, Line 3 Conversion failed when converting
date and/or time from character string.
I'm running SQL Server 2014 Management Studio.
Edited to take comments into account
destination-data's suggestion of using TRY_PARSE worked! Thanks everyone.
SQL does not know what to do with getdate()-90 -- subtract 90 days? 90 minutes? 90 years?
You need to use a function such as dateadd, e.g.
where convert(varchar(30),cast(substring(CA_NOTE, 12, 8) as datetime),102) < dateadd(dd, -90, getdate())
The problem is that you're still converting it to a VARCHAR. Try this instead:
CAST(substring(CA_NOTE, 12, 8) as datetime)

How to convert string date in BST and GMT format to SQL Server format as date type

I imported a table into SQL Server 2014 and I found that the date format is in BST and GST format. I want to create a view and change the whole column to SQL Server date type to perform operations. I don't mind truncating the time section.
Wed Apr 07 00:00:00 BST 1943
Tue Jan 08 00:00:00 GMT 1985
I was able to do it in Excel with the following formula but want to do it in SQL Server:
=IFERROR(DATEVALUE(MID(E2,9,2)&"-"&MID(E2,5,3)&"-"&RIGHT(E2,4)), "")
All I am looking for is
1943-04-07
1985-01-08
This solution assumes that every row in the source data follows the same format. If there are any fringe cases these will fail.
With SQL Server 2012, and higher, you have the handy DATEFROMPARTS function. This function returns a date when passed a year, month and day. These can be extracted with SUBSTRING and RIGHT from the source string.
Extracting the month number (1~12) is achieved by building an arbitrary date string (01-mmm-2000). This is cast into a date, from which the month number is extracted. Generally speaking I would't recommend using date strings in any format other than YYYY-MM-DD. However this avoids the use of a CTE, which OP was keen to do.
Example
/* Let's create some sample values to
* experiment with.
*/
DECLARE #Sample TABLE
(
DateVal VARCHAR(50)
)
;
INSERT INTO #Sample
(
DateVal
)
VALUES
('Wed Apr 07 00:00:00 BST 1943'),
('Tue Jan 08 00:00:00 GMT 1985')
;
/* Extracting the month number is achieved by first casting the 3 character month
* name as a full date, by appended a day and year. Then the month number is
* extracted from this.
*/
SELECT
s.DateVal,
SUBSTRING(s.DateVal, 9, 2) AS [Day],
MONTH(CAST('01-' + SUBSTRING(s.DateVal, 5, 3) + '-2000' AS DATE)) AS [Month],
RIGHT(s.DateVal, 4) AS [Year],
-- Reuse the values shown above.
DATEFROMPARTS(
RIGHT(s.DateVal, 4),
MONTH(CAST('01-' + SUBSTRING(s.DateVal, 5, 3) + '-2000' AS DATE)),
SUBSTRING(s.DateVal, 9, 2)
) AS [Date]
FROM
#Sample AS s
;
EDIT: The original solution contained a CTE, used to look up the month number from a 3 character month name. This has been replaced.
SELECT CONVERT(date, RIGHT(DateColumn, 4)+ '-' + RIGHT('0' + Convert(nvarchar, (Month(SUBSTRING(DateColumn, 5, 3) + '2016'))), 2) + '-' + SUBSTRING(DateColumn, 9, 2)) as dob
FROM MyTable
Your sample output doesn't match your input data. I think you meant 1985-01-08.
For a shorter solution, you can use CAST or CONVERT with style 107. It expects the string to be in the Mon dd, yyyy format:
SELECT CONVERT(datetime, SUBSTRING(DateColumn, 5, 6) + ', ' + RIGHT(DateColumn, 4), 107)
FROM MyTable

TSQL Logic in SSRS

I am building a report which has the header field as PropertyStatementForHalfyear Ending :<Date>
So in the DATE field I need to put either May 28 or Nov 28 depending on the date the report Runs
Whats The logic I need to write ??
For example if I run the report today i.e. June 22, I need to display PropertyStatementForHalfyear Ending : 28 Nov 2013
if I run it in December 2013, I need to display PropertyStatementForHalfyear Ending : 28 May 2014
You could use something like this:
DECLARE #DateThreshold1 DATE = '20130528'
DECLARE #DateThreshold2 DATE = '20131128'
DECLARE #CurrentDate DATE = '20131201'
IF #CurrentDate > #DateThreshold2
SELECT CONVERT(VARCHAR(50), DATEADD(YEAR, 1, #DateThreshold1), 106)
ELSE IF #CurrentDate > #DateThreshold1
SELECT CONVERT(VARCHAR(50), #DateThreshold2, 106)
ELSE
SELECT CONVERT(VARCHAR(50), #DateThreshold1, 106)
For dates from 20130101 through 20130528, this will return 28 May 2013
For dates from 20130529 through 20131128, this will return 28 Nov 2013
For dates past 20131128, this will return 28 May 2014
You can easily package this up into a function or a SSRS code snippet
If you're not into IF/CASE statements, like me:
with dt as
(select CAST('2013-11-28' as datetime) dt) --dt becomes your datetime column.
, ymdt as (select
DATEPART(year, dt) y,
DATEPART(month, dt) m,
DATEPART(day, dt) d,
dt
from dt) --split into year, month and date for readability
select y, m, d, dt,
DATEADD(month, 5 + d/28 - (m + d/28) % 6, --add months depending on month and day
DATEADD(day, 28 - d --go to the correct day
, dt) --start calculation from dt (the sql date functions' parameter order has always baffled me)
) HalfYearEndDate
from ymdt
The SQL engine merges all of this into one big fat constant scan or scalar expression on your datetime column.
You should create a SQL or VB function for this if you need this in other reports and also so it doesn't clutter up your queries.
Also: Don't do text formatting in T-SQL unless absolutely necessary! Return a datetime column and do it in the report itself. The format you need to set on the textbox is "dd MMM yyyy" (without the quotes when using the designer).

Resources