Put a date variable in quotes in SQL - 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"

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)

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)

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)

Convert Date datatype to datetime datatype and add static time

I'm at my wits end... Hope you all can help. I have a date column entryexpire in sql table, eg:
2013-04-12
I need to convert it to a datetime with all values in entryexpire to have 24:00:00 appended to new values, eg:
2103-04-12 24:00:00
I've tried cast, covert, adding new columns and concatenation ... All failed me.
Add new column col2 (Datetime). Issue update:
update table t1 set col2 = cast(col1, datetime) // db specific function
Drop column Col1.
Rename col2 to col1
I mean, there are few other ways of doing it as well
24:00:00 is not really an option for a date - you'd be into the next day. Here's a select statement you can use to tailor a date to your needs, but about the closest you will get to the end of the day is 23:59:59.997
DECLARE #MYDATE varchar(50) = '2013-04-12'
SELECT DATEADD(DAY,1,DATEADD(Ms,-2, CAST(#MYDATE AS DATETIME)))
This returns 2013-04-12 23:59:59.997
Alternately, you could have two different varchar columns (which it seems you tried), and query them like this to get a datetime
DECLARE #MYDATE varchar(50) = '2013-04-12'
declare #mytime varchar(50) = ' 23:59:59.998'
select CAST(#mydate + #mytime as datetime)
Again, using 23:59:59.999 causes the select to return 2013-04-13 00:00:00.000. Not sure why.
If anyone had same problem this is how i solved. I created a char column
temptime
and added a value of 23:59:00 to all records in database into that column with an update command.
i then created another column as datetime
entryexpiredatetime
with my entryexpiredate as a char and temptime as char column i used #folksymAndrews code as follows:
Blockquote
update [table] set entryexpiredatetime = CAST(ENTRYEXPIREDATE+timetime as datetime)
Blockquote
then i dropped temptime column and was left with my original entryexpiredate and my needed entryexpiredatetime columns.
Thanks for all your help. This was the best way i felt i could accomplish the task but im sure there is a less invasion way.

T-SQL 2008 Convert Date and time string to datetime

I have two columns in my table, one to capture time and one to capture date. Unfortunately, both are varchar(). I need to take the two fields, concatenate them together, and then convert them to datetime.
I am trying to accomplish that with this:
select CONVERT(datetime,(select txt_returned_date+' '+CONVERT(varchar(20),CONVERT(TIME,txt_time_returned))),126)
from table_name
I am getting this error message:
Conversion failed when converting date and/or time from character string.
The date is being captured as "20130308" as a string. Time is being captures as "4:27 PM" as a string
What I am doing here is converting the string of the time to TIME, then back to varchar. Then I am concatenating them together. This works by itself, but once I introduce the CONVERT(datetime) to the whole query, it is giving me the error.
Any help to try to accomplish this is helpful. Thanks!
You can concatenate the DATE and TIME values together once they have been converted to a DATETIME. Here's a sample to play with that shows concatenating a DATE column and a TIME column that have been stored as VARCHAR:
-- Set up some variables to test with
DECLARE #myTime TIME = GETDATE()
, #myDate DATE = GETDATE()
, #myTimeTxt VARCHAR(16)
, #myDateTxt VARCHAR(10);
-- Initialize your variables
SELECT #myTimeTxt = #myTime
, #myDateTxt = #myDate;
-- Display your separated values
SELECT #myDateTxt, #myTimeTxt;
-- Display your concatenated value
SELECT CAST(#myDateTxt AS DATETIME) + CAST(CAST(#myTimeTxt AS TIME) AS DATETIME);
You can use this option
DECLARE #date date = '20010101',
#time time = '01:01:01'
SELECT CAST(#date AS datetime) + #time
Result:2001-01-01 01:01:01.000
Demo on SQLFiddle
Are you using SQL 2012? If so you may be able to use the datetimedromparts function to achieve this. If not for this specific example, it's always good to know for the future :)
http://technet.microsoft.com/en-gb/library/hh213233.aspx