Extract date from string and insert into field Microsoft SQL Server 2012 - sql

Say I have a field UserAddedInfo with a string "User was added to the system and removed from list on 16/05/2016 by User Annon" and a field DateAdded in the same table.
Is there any way in SQL to extract that 16/05/2016 date from the string field and insert it into the DateAdded field as a datetime?
The date in the string is always going to be dd/MM/yyyy.
Thanks!

Use PATINDEX to get the start position of the date string in the column and extract 10 characters from that position. To convert the extracted string to date, use CONVERT with format 103.
103 = dd/mm/yyyy
select
convert(date,
substring(UserAddedInfo,patindex('%[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]%',UserAddedInfo),10)
,103)
from table_name
where patindex('%[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]%',UserAddedInfo) > 0
To update the dateadded field in the table, use
update table_name
set dateadded = convert(date,
substring(UserAddedInfo,patindex('%[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]%',UserAddedInfo),10)
,103)
where patindex('%[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]%',UserAddedInfo) > 0
Use try_cast or try_convert to return null when the substring returns invalid dates.
select
try_cast(
substring(UserAddedInfo,patindex('%[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]%',UserAddedInfo),10)
as date)
--or
--try_convert(date,
--substring(UserAddedInfo,patindex('%[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]%',UserAddedInfo),10)
--)
from table_name
where patindex('%[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]%',UserAddedInfo) > 0

You can use patindex to find date string, and use cast to convert it to datetime
select
cast(substring('User was added to the system and removed from list on 27/08/2014 by User Annon',
patindex('%[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]%',
'User was added to the system and removed from list on 27/08/2014 by User Annon'), 10) as datetime)

Related

Cast function SQL query

I have a column 'Created date' of string type (which has values like 19-01-2022, 05/02/1992 etc). I need to write a query to get the data from this table Orders where created date is greater than Jan 1st 2019. How can I write the query using cast function?
if you have just two string formats i.e. dd-mm-yyyy and dd/mm/yyyy then you can get through inline query only.
SELECT * FROM TABLENAME WHERE CONVERT(DATE,createdDate,103) >= '2019-01-01'
or if you passing search values in dd/mm/yyyy then
SELECT * FROM TABLENAME WHERE CONVERT(DATE,createdDate,103) >= CONVERT(DATE,'01/01/2019',103)
in case if you have more other types of string stored like mm/dd/yyyy then add one column to your table with datetime datatype. you only knowing the type of data in created date so you need to convert them into dates one by one. like for dd-mm-yyyy and dd/mm/yyyy you can convert to date.
Following is example of query for conversion
DECLARE #strdate VARCHAR(50)
SET #strdate = '19-01-2022'
SELECT CONVERT(DATE,#strdate,103)
SET #strdate = '05/02/2022'
SELECT CONVERT(DATE,#strdate,103)
SET #strdate = '12/31/2022'
SELECT CONVERT(DATE,#strdate,110)
you need to update newly added column from createddate column using update query and then apply your function on that
UPDATE TABLENAME SET newcreatedDate = CONVERT(DATE,createdDate,103) WHERE newcreatedDate IS NULL
and perform search query
SELECT * FROM TABLENAME WHERE newcreatedDate >= '2019-01-01'
or if you passing search values in dd/mm/yyyy then
SELECT * FROM TABLENAME WHERE CONVERT(DATE,newcreatedDate ,103) >= CONVERT(DATE,'01/01/2019',103)

date time stored as varchar in sql how to filter on varchar

I am working on a project in which dates and times ar stored as a varchar e.g. "30-11-2017,7:30" first date in dd-mm-yyy format and then time separated with a comma. I am trying to filter on it but it is not working correctly kindly guide me how to filter data on date.
select *
from timetrack
where startDateAndTime >= '30-11-2017,7:30'
In attached image records have been shown. When I apply above query it shows no records
You can easily convert your date to SQL datatype datetime uisng parse function, for example select parse('30-11-2017,7:30' as datetime using 'it-IT').
So, in your case, you can apply this function in where clause, so you can easily apply comparison between dates:
select *
from timetrack
where parse(startDateAndTime as datetime using 'it-IT') >= '2017-11-30 07:30:00.000'
Your format is apparently italian :) But you have to specify your own date in the format convertable to datetime, as I have done in above example.
NOTE: parse is available starting with SQL Management Studio 2012.
Unless you are using ISO date format (yyyy-MM-dd HH:mm:ss or close) applying ordering (which inequalities like greater than or equal use) will not work: the date order is disconnected from the string ordering.
You'll need to parse the date and times into a real date time type and then compare to that (details of this depend on which RDBMS you are using).
If, you want to just filter out the date then you could use convert() function for SQL Server
select *
from timetrack
where startDateAndTime >= convert(date, left(#date, 10), 103)
Else convert it to datetime as follow
select *
from timetrack
where startDateAndTime >= convert(datetime, left(#date, 10)+' ' +
reverse(left(reverse(#date), charindex(',', reverse(#date))-1)), 103)
You need the date in a datetime column, Otherwise you can't filter with your current varchar format of your date.
Without changing the existing columns, this can be achieved by making a computed column and making it persisted to optimize performance.
ALTER TABLE test add CstartDateTime
as convert(datetime, substring(startDateAndTime, 7,4)+ substring(startDateAndTime, 4,2)
+ left(startDateAndTime, 2) +' '+ right(startDateAndTime, 5), 112) persisted
Note: this require all rows in the column contains a valid date with the current format
Firstly, you need to check what is the data that is entered in the 'startDateAndTime' column,then you can convert that varchar into date format
If the data in 'startDateAndTime' column has data like '30-11-2017,07:30', you would then have to convert it into date:
SELECT to_date('30-11-2017,07:30','dd-mm-yyyy,hh:mm') from dual; --check this
--Your query:
SELECT to_date(startDateAndTime ,'dd-mm-yyyy,hh:mm') from timetrack;

How to update/Change the date format to MM/dd/yyyy from dd/MM/yyyy format in sql server?

In my db DOB is saved in dd/mm/yyyy format. i want to change the DOB date format to MM/dd/yyyy. How can i do that?
First i want to know which datatype you are using for saving your date value. There is nothing provided with your code no sample code, table details nothing. anyway
i think your 'date of birth' field datatype is datetime,then you can use the following example
create table checktable(
ID int,
name nvarchar (30),
dob datetime);
Example data insert into the table
insert into checktable(ID,name,dob) values(10,'myname','03/01/2014');
//..........
select * from checktable
//Use CONVERT() it will give you the desired output
SELECT TOP 1 ID, dob,CONVERT(varchar,dob,101) 'mm/dd/yyyy'
FROM checktable
UPDATE
if your datatype is varchar and now it is in the format mm/dd/yyyy and you want to change it into dd/mm/yyyy format then use the following example it will help you
create table checktable1(
ID int,
name nvarchar (30),
dob varchar(20));
// insert sample data
insert into checktable1(ID,name,dob) values(10,'myname','21/05/2010');
select * from checktable1
// change the format using substring()
select * FROM checktable1
select dob,substring(dob,4,3)+substring(dob, 1, 3)+substring(dob, 7, 4) from checktable1
It will give you result in 05/21/2010 (mm/dd/yyyy)format
Microsoft SQL: https://msdn.microsoft.com/en-us/library/ms187928.aspx
Syntax for CONVERT:
CONVERT ( data_type [ ( length ) ] , expression [ , style ] )
use example:
SELECT CONVERT(VARCHAR(10), GETDATE(), 101) AS [MM/DD/YYYY]
For other databases search Date and Time Functions in documentation.
The CONVERT() function is a general function that converts an expression of one data type to another.
The CONVERT() function can be used to display date/time data in different formats.
http://www.w3schools.com/sql/func_convert.asp
if your data type is DateTime then no need to convert it, in later you can convert its format as you want but if your are using varchar or nvarchar
then you can use CONVERT() as below
SELECT convert(datetime, '23/10/2016', 103)
Result : 2016-10-23 00:00:00.000
if just want to conver in date then
SELECT convert(date, '23/10/2016', 103)
Result : 2016-10-23
for more information and other formats
http://www.sqlusa.com/bestpractices/datetimeconversion/
and if you just want to convert string to sting then
SELECT CONVERT(varchar,'23/10/2016',101)
Result : 23/10/2016
This is the query to show all data in dd/mm/yyyy format.Type your column name that contains date in place of datecolumnname and your table name in place of tablename in below query:
select convert(varchar,datecolumname,103) as datecolumname from tablename

SQL server 2012 error converting date from string when selecting date with like

In my table, I have a datetime NULL field called logDate.
The format stored: 2014-03-28 12:24:00.000
I have a form and the log date is one of the fields for searching logs.
The user will enter the date like 2014-03-28
So in my SELECT procedure I need to use a LIKE:
#logDate datetime =NULL
.
.
SELECT .. FROM mytable WHERE
(#logDate IS NULL OR CONVERT(VARCHAR, #logDate, 102) LIKE '%'+logDate+'%')
I execute the procedure:
EXEC dbo.SELECT_mytable #logDate= '2014-03-28'
But I get the following error:
Conversion failed when converting date and/or time from character string.
What am I doing wrong?
You also need to convert the logdate column to a varchar, I think you have your LIKE the wrong way around as you are trying to find the user entered date within the date column, so try:
SELECT .. FROM mytable WHERE
(#logDate IS NULL
OR '%'+CONVERT(VARCHAR, #logDate, 102)+'%' LIKE CONVERT(VARCHAR, logDate, 102))
As others have indicated (and I should have pointed out) you shouldn't be converting Dates to Strings in-order to search date columns, much better to keep everything in a DateTime format for performance.
This will work, provided that you change your stored procedure to expect the #logDate parameter as a DateTime:
SELECT .. FROM mytable WHERE
(#logDate IS NULL
OR logDate = #logDate)
I get the impression that you went down the string comparison route because you wanted to ignore the time element and just search on date, if that is the case you can strip the time from both elements and just match on date by doing this:
IF #logDate IS NOT NULL
BEGIN
// Remove any time element
SET #logDate = DATEADD(dd,0, DATEDIFF(dd,0,#logDate))
END
SELECT .. FROM mytable WHERE
(#logDate IS NULL
OR DATEADD(dd,0, DATEDIFF(dd,0,logDate)) = #logDate)

finding data lying between a specific date range in sql

I want to find records from my database which lie between any user input date range(say between 10/2/2008 to 26/9/2024). I tried using
SELECT NAME
,TYPE
,COMP_NAME
,BATCH_NO
,SHELF
,MFG_DATE
,EXP_DATE
,QTY
,VAT
,MRP
FROM STOCK_LOCAL
WHERE
convert(VARCHAR(20), EXP_DATE, 103)
BETWEEN convert(VARCHAR(20), #MEDICINEEXP_DATE, 103)
AND convert(VARCHAR(20), #MEDICINEEXPDATE, 103)
but with this query i need to enter perfect date range which is available in my database, it is not giving me data lying in between any date entered.
Thanks in advance
Since it is a poolr designed schema there isnt going to be any decent/Efficient solution for this.
In sql server if you are storing Date or Date & Time data. Use the Data or DATETIME datatypes for your columns.
In your case you are trying to compare a string with passed date. and even when you tried to convert the string (Date) into date datatype you didnt do it correctly.
My suggestion would be Add new columns to your table with Date datatype and update these columns with existing date/string values.
For now you can convert the Date(string) into date datatype using the following code.
DECLARE #MEDICINEEXP_DATE DATE = 'SomeValue1'
DECLARE #MEDICINEEXPDATE DATE = 'SomeValue1'
SELECT query....
FROM TableName
WHERE
CAST(
RIGHT(EXP_DATE, 4)
+SUBSTRING(EXP_DATE,CHARINDEX('/',EXP_DATE)+1,2)
+LEFT(EXP_DATE,2)
AS DATE) >= #MEDICINEEXP_DATE
AND CAST(
RIGHT(EXP_DATE, 4)
+SUBSTRING(EXP_DATE,CHARINDEX('/',EXP_DATE)+1,2)
+LEFT(EXP_DATE,2)
AS DATE) <= #MEDICINEEXPDATE
Note
This solution will get you the expected results but very inefficient method. It will not make use of any indexses on your EXP_DATE Column even if you have a very buffed up index on that column.