Need to format date in SQL from string using charindex - sql

I am trying to format a date in mm/dd/yyyy from string data using charindex, the date in the string is yyyymmdd. I have tried using convert, cast, castconvert.
If anyone could help that would be great! I have sample code
CONVERT (
VARCHAR (10)
, CASE
WHEN CHARINDEX ('^3507=', reg.BetaRequestString) = 0 THEN
''
ELSE
RIGHT(LEFT(reg.BetaRequestString, CHARINDEX ('^3507=', reg.BetaRequestString) + 13), 8)
END
, 101

declare #a nvarchar(10)
set #a='20180203'
select
convert(nvarchar(10),substring(#a,5,2)+'/'+substring(#a,7,2)+'/'
+substring(#a,1,4),101)

It appears you want this:
CASE WHEN CHARINDEX ('^3507=', reg.BetaRequestString) = 0
THEN ''
ELSE CONVERT(VARCHAR(10),RIGHT(LEFT(reg.BetaRequestString, CHARINDEX ('^3507=', reg.BetaRequestString) + 13), 8), 101)
END

When you know your input date format , you can split the parts and reorganise the date.
declare #date varchar(100)='20021230' ,
#Year int,#month int ,#day int
select #year=Substring(#date,1,4) ,#month=SUBSTRING(#date,5,2),#day=SUBSTRING(#date,7,2)
select convert(VARCHAR(10),(DATEFROMPARTS(#year,#month,#day)),101)
output-12/30/2002

You can also use datetime style in convert function:
https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql#date-and-time-styles
DECLARE #yyyymmdd sysname = '20180101'
SELECT CONVERT(sysname, CONVERT(datetime, #yyyymmdd, 112), 101)

Related

How to convert a string into datetime in SQL Server?

I am writing a SQL query to convert string to datetime:
SELECT CAST('2017-04-07.15-23-44' AS datetime)
When I am converting it to datetime getting an error
varchar data type to datetime data type resulted in out of range value.
Split the string with the . as delimiter and in the 2nd part replace all '-' with ':'.
Concatenate the 2 parts again and then cast it to DATETIME:
DECLARE #d VARCHAR(20) = '2017-04-07.15-23-44';
SELECT CAST(LEFT(#d, CHARINDEX('.', #d) - 1) + ' ' +
REPLACE(SUBSTRING(#d, CHARINDEX('.', #d) + 1, LEN(#d)), '-', ':')
AS datetime
)
See the demo.
You can try the following to format as an ISO date
declare #date varchar(20)='2017-04-07.15-23-44'
select Cast(Replace(Replace(Stuff(Stuff(#date,14,1,':'),17,1,':'),'-',''),'.',' ') as datetime)

SQL convert string(date or text) to date

I have a database which has a column called stringNextDue that contains data like dates (UK format) and text (e.g "overdue", "completed")
I am trying to create a view that shows courses that are due within a month from now:
WHERE
CONVERT(DATETIME, mt.stringNextDue , 103) < DATEADD(MONTH, 1, GETDATE())
This throws an error:
Conversion failed when converting date and/or time from character string.
Which is probably due to the fact that stringNextDue may contain actual strings of text.
I tried using
WHERE
ISDATE(mt.NextDateString) = 1
AND CONVERT(DATETIME, mt.stringNextDue , 103) < DATEADD(MONTH, 1, GETDATE())
But ISDATE only accepts US date formats therefore ignoring a lot of actual dates as strings
Tried set dateformat 'dmy', which fixed the IsDate issue, but it cannot be used in views.
Any suggestions?
Server update is not an option
If you cannot use the new TRY_CONVERT you might use a function like this:
Attention: This will not catch a wrong date like 31.06.2016, you'd have to modify the BETWEEN 1 AND 31 if you need this...
Attention2: If your text might include characters forbidden in xml you should replace < with <, > with > and & with & ...
CREATE FUNCTION dbo.TestDate(#TestString VARCHAR(100))
RETURNS DATE
AS
BEGIN
DECLARE #x XML=CAST('<x>' + REPLACE(#TestString,'.','</x><x>') + '</x>' AS XML)
DECLARE #p1 VARCHAR(10) = #x.value('x[1]','varchar(10)');
DECLARE #p2 VARCHAR(10) = #x.value('x[2]','varchar(10)');
DECLARE #p3 VARCHAR(10) = #x.value('x[3]','varchar(10)');
IF LEN(#p1)=2 AND ISNUMERIC(#p1)=1 AND CAST(#p1 AS INT) BETWEEN 1 AND 31
AND LEN(#p2)=2 AND ISNUMERIC(#p2)=1 AND CAST(#p2 AS INT) BETWEEN 1 AND 12
AND LEN(#p3)=4 AND ISNUMERIC(#p3)=1 AND CAST(#p3 AS INT) BETWEEN 1900 AND 2100
RETURN CONVERT(DATETIME, #TestString , 103);
RETURN NULL;
END
GO
SELECT
dbo.TestDate('overdue') AS SureNoDate
,dbo.TestDate('01.04.2016') AS EuropeanDate
,dbo.TestDate('2016.04.01') AS WrongFormat
,dbo.TestDate('01.13.2016') AS BadDate;
GO
DROP FUNCTION dbo.TestDate;
The result
SureNoDate EuropeanDate WrongFormat BadDate
NULL 2016-04-01 NULL NULL
You might pass back a valid date (RETURN GETDATE() ?) instead of RETURN NULL for your comparisson outside. This depends on your needs...
It should be possible to replace WHERE clause using this:
SELECT *
FROM
-- sample data
(values('2015-01-01'),('01-01-2015'), ('x-x-x-x')) mt(NextDateString)
-- Replace WHERE statement with the following
CROSS APPLY
(
SELECT
RIGHT('0000'+PARSENAME(REPLACE(mt.NextDateString, '-', '.'), 1),4) yyy,
RIGHT('0000'+PARSENAME(REPLACE(mt.NextDateString, '-', '.'), 2),4) mmm,
RIGHT('0000'+PARSENAME(REPLACE(mt.NextDateString, '-', '.'), 3),4) ddd
) x
WHERE
x.yyy BETWEEN '1950' AND '2050'
AND x.mmm BETWEEN '0001' AND '0012'
AND x.ddd BETWEEN '0001' AND '0031'
AND ISDATE(mt.NextDateString) = 1
AND x.yyy+x.mmm+x.ddd < CONVERT(char(8), DATEADD(MONTH, 1, GETDATE()), 112)
Result:
NextDateString yyy mmm ddd
01-01-2015 2015 0001 0001
Thank you for suggestions,
I fixed it by setting language to British on user settings
EXEC sp_defaultlanguage 'username', 'british'

SQL Date/Time Format

How to convert date/time from 20150323153528 to 2015-03-23 15:35:28.000. I need this to filter based on the getdate(). Thanks in advance.
Select * from table
Where 20150323153528 > GETDATE() - 7
Statement to convert date to your requirement
DECLARE #Date varchar(20) = '20150323153528'
Select * from table Where
CONVERT(DATETIME, CONVERT(CHAR(8), #Date), 121) + ' ' + stuff(stuff(right('000000' + cast(#Date as varchar),6),5,0,':'),3,0,':') as DATETIME > GETDATE() - 7
In MS SQL you could use
DECLARE #Date varchar(20) = '20150323153528'
Select * from table Where CAST(convert(varchar,#Date) as datetime) > GETDATE() - 7
Please read this page.
SELECT convert(varchar, getdate(), 120) — yyyy-mm-dd hh:mm:ss(24h)
Note: I assume this is a Microsoft SQL Server environment using T-SQL:
The formatting of date / datetime values is not a concern of T-SQL. You should do that in your presentation-layer (i.e. your frontend code).
If you have date/time values represented as integers of the form 20150323153528 then you cannot use them in T-SQL. You need to convert them to strings (preferably in ISO-8601 format) for SQL Server to successfully internally convert them to datetime (or datetimeoffset) values which can then be compared with other datetime values.
I suggest performing the conversion in your application code before you send it to SQL, as a datetime-typed parameter value, like so:
Int32 weirdDateValue = 20150323153528;
String s = weirdDateValue.ToString( CultureInfo.InvariantCulture );
String dtValueAsIso8601 = String.Format("{0}-{1}-{2} {3}:{4}:{5}.{6}",
s.Substring(0, 4), s.Substring(4, 2), s.Substring(6, 2),
s.Substring(8, 2), s.Substring(10, 2), s.Substring(12, 2), s.Substring(14)
);
DateTime dtValue = DateTime.ParseExact( dtValueAsIso8601, "yyyy-MM-dd HH:mm:ss.fff" );
cmd.Parameters.Add("#dtValue", SqlDbType.DateTime).Value = dtValue;
In T-SQL the process is pretty much the same, except using MID - note that MID uses 1-based character indexes instead of 0-based:
DECLARE #input int = 20150323153528
DECLARE #s varchar( 14 ) = CONVERT( #input, nvarchar(14) )
DECLARE #dtStr varchar( 24 ) = MID( #s, 1, 2 ) + '-' + MID( #s, 3, 2 ) + '-' + MID( #s, 5, 2 ) + ' ' + -- etc...
DECLARE #dt datetime = CONVERT( #dtStr, datetime )
SELECT
*
FROM
[table]
WHERE
#dt > GETDATE() - 7
If the integer values are stored in an actual column instead of a parameter you'll need to convert the logic into a scalar UDF which performs the conversion. I strongly suggest you change the table's design to add a strongly-typed datetime column and permanently store the value there, and then drop the datetime-as-int column:
CREATE FUNCTION ConvertIntDateIntoDateTime(#dateAsInt int) RETURNS datetime AS
BEGIN
-- same code as above minus the SELECT statement
RETURN #dt
END
Used in an inner subquery to allow the data to be accessed in WHERE statements, like so:
SELECT
*
FROM
(
SELECT
*,
dbo.ConvertIntDateIntoDateTime( someDateColumn ) AS someDateColumn2
FROM
[table]
) AS FixedTable
WHERE
FixedTable.someDateColumn2 > GETDATE() - 7

Converting smalldatetime datatype to varchar datatype

How to convert smalldatetime to varchar? I've tried everything from http://msdn.microsoft.com/en-us/library/ms187928.aspx, but it didn't work.
I want to convert smalldatetime into varchar, because I want to use it in select like this:
select 'Some text'+#Date
thanks in advance
'121' is the format of the date in this case 'yyyy-mm-dd hh:mi:ss.mmm(24h)',
char(16) is the number of characters you wish to include, first 16 in this case.
select 'Some text'+convert(char(16), #date, 121)
Cast and Convert
SELECT CONVERT(VARCHAR(20), YourDateColumn, 103) as NewColumnName
here 103 make the date format as dd/mm/yyyy
if you want mm/dd/yyyy, you have to use 100
Here is a more up to date link.
The expression
'Some text ' + CONVERT(VarChar(20), [Data])
works fine, fiddle here, what style did you want?
Prueba con esto
DECLARE #FechaDesde datetime2
SET #FechaDesde = ''
SELECT LEFT(CONVERT(VARCHAR, #FechaDesde, 120), 10)
print #FechaDesde
---FECHA HASTA
DECLARE #FechaHasta datetime2
SET #FechaHasta = ''
SELECT LEFT(CONVERT(VARCHAR, #FechaHasta, 120), 10)
print #FechaHasta
SELECT * from compras where fec_emis between #FechaDesde and #FechaHasta

ddmmyyyy to sql datetime in SQL

I need to convert a nvarchar value to datetime in T-SQL. The value is in ddmmyyyy format, e.g. 23072009
I need to convert to datetime in T-SQL.
I tried
select convert(datetime, '23072009', 103)
But it is throwing error.
"The conversion of a nvarchar data type to a datetime data type
resulted in an out-of-range value."
Any idea
Thanks
Rebuild your format to yyyymmdd.
declare #D varchar(8)
set #D = '23072009'
select cast(right(#D, 4)+substring(#D, 3, 2)+left(#D, 2) as datetime)
The style 103 will accept strings with dd/mm/yyyy format. So your code should be
declare #date varchar(8)
set #date='23072009'
select convert(datetime,stuff(stuff(#date,5,0,'/'),3,0,'/') , 103)
You can define custom function like this:
CREATE FUNCTION [dbo].[GetCustomDate] (#customDateString NVARCHAR(MAX))
RETURNS DATETIME
AS
BEGIN
RETURN CONVERT(DATETIME, RIGHT(#customDateString, 4) + RIGHT(LEFT(#customDateString, 4), 2) + LEFT(#customDateString, 2))
END
Change VARCHAR (dd-mm-yyyy) to date (yyyy-mm-dd) in SQL Server.
DECLARE #VarDate VARCHAR(10)
SET #VarDate = '22-02-1994'
SELECT CONVERT(DATETIME, CONVERT(VARCHAR, CONVERT(DATE, #VarDate, 103), 102))
You need to cast a string and not a int. Put some quotes:
convert(datetime, '23072009', 103)
And 103 gets the string like 'dd/mm/yyyy' and not 'ddmmyyyy'.