Cast function SQL query - sql

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)

Related

Put a date variable in quotes in SQL

I have declared a variable that is getting date from an output activity.
vGetDate= 2021-03-20 and want to use this value in my query to fetch the record after that date. eg: (Select * from ABC where UpdatedDate > vGetDate) . I want to put single quotes to date in order to make it work properly.
Below is my code
declare #date1 varchar(20) = activity.output i.e will return o/p in this format(without quotes) : 2021-03-22
select *
from abc
where format([UpdatedDtTm],'yyyy-MM-dd') > cast(#date1 as datetime).
I am using this but since date1 variable has date without quotes , thats why this where condition is not working fine.
Implied data conversions inside a where clause can be a significant performance and/or reliability issue and should be avoided.
As I don't know anything about the activity.output(2021-03-22) or why you cannot use activity.output('2021-03-22') let's try to consider a simplified case. On the assumption that the column [UpdatedDtTm] is indeed a datetime column, then you can compare that column to a datetime variable without needing format() or cast(), like this:
declare #Date1 datetime = '20210322'
select * from abc
where [UpdatedDtTm] > #Date1
Keep in mind that any date related data types are NOT stored "in a format" they are actually numeric and any format that we use to understand the date or time is applied rather like typing 44279 into an Excel cell and then formatting it to a date which displays as 2021-03-24 (if your default date format is yyyy-mm-dd). It's not exactly the same in SQL Server but quite similar.
I am ignoring activity.output but assuming it is a string. Likewise I am assuming [UpdatedDtTm] is a datetime column.
declare #Date1 datetime = try_cast(activity.output as datetime)
select * from abc
where [UpdatedDtTm] > #Date1
or
declare #Date1 datetime = try_convert(datetime,activity.output,121)
select * from abc
where [UpdatedDtTm] > #Date1
Note that try_cast or try_convert will not fail if the activity.output isn't a valid date but they will return NULL in such cases and your query will return no rows.
Once you have passed the value into #Date1 then you just compare datetime column to datetime variable. Try to ignore anything to do with "format"

Converting string to datetime works with select but nor update (T-SQL)

I have a table in my database that has has both the original user input date string, then tries to get the datetime from that by using CONVERT
CREATE TABLE #UserInput
(
actualDate DATETIME NULL,
dateString VARCHAR(50) NULL
)
The statement
SELECT CONVERT(DATETIME, dateString)
FROM #UserInput
works fine, and correctly converts the strings to datetime.
However, when I try to set the actualDate column, using the statement
UPDATE X
SET X.actualDate = CONVERT(DATETIME, X.dateString)
FROM #UserInput X
I get the error:
Conversion failed when converting date and/or time from character string.
Since I can run the select, I know all the dateStrings are formatted correctly and can be converted. So then why am I unable to do so with the update?
The specific format I've been testing with is mm/dd/yyyy hh:mm, but the solution would need to handle other formats as well.
I appreciate any help on this, thanks.
CREATE TABLE #UserInput (
actualDate datetime NULL,
dateString varchar(50) NULL)
insert #UserInput(dateString) values('20181231 12:15')
SELECT CONVERT(datetime, dateString)
FROM #UserInput
UPDATE X
SET X.actualDate = CONVERT(datetime, X.dateString)
FROM #UserInput X
select * from #UserInput
I tested it for two format yyyymmdd hh:mm and mm/dd/yyyy hh:mm this code working correctly. I didn't get any error for update or select run.
The simply solution is try_convert():
UPDATE X
SET X.actualDate = TRY_CONVERT(DATETIME, X.dateString)
FROM #UserInput X ;
I suspect the problem is that you are not seeing all the rows in X -- just a few that match. To test this, run:
select X.*
from #userinput X
where try_convert(datetime, x.dateString) is null;

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

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)

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.

How to convert GetDate() in 1 Jan 2014 format?

I using a query where I am selecting some attributes from the table based on a where condition. My where condition is-
date>GetDate();
I have tried this-
SELECT TOP 2 img,name,substring(description,1,80) as
description,Convert(nvarchar,date,106) as date
FROM tbl_test
where date>=Convert(nvarchar,GetDate(),106)
order by date Asc;
This query is running fine but showing different result as compared to a different query of similar kind in which I am not converting the date format.
SELECT TOP 2 img,name,substring(description,1,80) as description,date
FROM tbl_test
where date>=GetDate()
order by date Asc;
Please guide me where I am doing wrong?
Your first query will convert getdate() into nvarchar data type and it will compare date with string while 2nd query will compare 2 dates. So 2nd option is better. Still if you want to convert date into string then check then use 102 format like
WHERE CONVERT(varchar(20),date,102) >= CONVERT(varchar(20), getdate(),102)
For select column you can use format which you want like
SELECT CONVERT(varchar(20),date,106)
Final Query is :
SELECT TOP 2
img,
name,
SUBSTRING(description,1,80) as description,
CONVERT(varchar(20),date,106) as [DisplayDate]
FROM tbl_test
WHERE CONVERT(varchar(20),date,102) >= CONVERT(varchar(20), getdate(),102)
ORDER BY date ASC;
Without convert to varchar, you can cast getdate() to date to remove time part :
SELECT TOP 2
img,
name,
SUBSTRING(description,1,80) as description,
CONVERT(varchar(20),date,106) as [DisplayDate]
FROM tbl_test
WHERE date >= CAST(getdate() as date)
ORDER BY date ASC;
SQL Fiddle Demo
DECLARE #Date Datetime;
SET #Date = GETDATE();
SELECT CONVERT(VARCHAR(12), #Date, 113) AS Date
RESULT
╔══════════════╗
║ Date ║
╠══════════════╣
║ 01 Jan 2014 ║
╚══════════════╝
Edit
as Upendra Chaudhari has explained that when you do comparing column Date with a string =Convert(varchar(20),GetDate(),102),
what is actually happening behind the scenes is Convert(varchar(20),GetDate(),102) returns a string 2014.01.01 but to compare this string with a Datetime column SQL Server does an implicit conversion to compare both values. Sql Server have to have both values in the same datatype to compare them.
Now datatype Datetime has Precedence over nvarchar/varchar datatype so sql server converts the string into datetime datatype which returns something like
SELECT CAST('2014.01.01' AS DATETIME)
Result : 2014-01-01 00:00:00.000
Now in this process of converting your values to string and then back to datetime you have actually lost all the time values in your comparing values. and this is the reason why you are getting unexpected results back.
so make sure whenever you are comparing to have exactly the same datatype on both sides and take control of any data conversions in your code rather then sql server doing datatype conversions for you.
I hope this will explain you why you are getting different results .
You may try:
where date>=CONVERT(VARCHAR(11), GETDATE(), 113)