I try to get selected the current month data by using SQL Server LIKE but it not get the any result. My when I run same code in my SQL it get the original result. What is error of my query? This query I want to run in SQL Server.
SELECT EnrolledID, Date, Time
FROM dbo.view_attendance
WHERE Date LIKE '2019-08%'
ORDER BY Date,Time;
Date in the SQL Server database date is something like that 2019-08-14 00:00:00.000.
Even though you have asked for a LIKE, I would recommend using the following format:
SELECT [EnrolledID]
, [Date]
, [Time]
FROM dbo.view_attendance
WHERE [Date] >= '20190801' and [Date] < '20190901'
ORDER BY [Date], [Time];
Although there is no syntax error in the case of using LIKE over DATETIME columns, I would recommend using LIKE only when trying to parse STRING values, in search for a certain pattern.
LIKE will not work with DATETIME columns and will not return results. If your column is of type DATETIME then I recommend using the above method.
MySql does implicit conversions between data types in expressions like your case:
Date LIKE '2019-08%'
so MySql converts Date to varchar and the expression returns a valid result because both operands are treated as varchars.
You can find more here: https://dev.mysql.com/doc/refman/8.0/en/type-conversion.html
SQL Server does not do this, so you must explicitly do the conversion or use a function like:
WHERE FORMAT(Date, 'yyyy-MM') = '2019-08'
if [Date] column is DateTime Type, try this :
declare #currentMonth int = datepart(MONTH,GETDATE())
declare #currentYear int = datepart(YEAR,GETDATE())
SELECT [EnrolledID]
, [Date]
, [Time]
FROM dbo.view_attendance
WHERE DATEPART(year,[Date]) = #currentYear And DATEPART(MONTH,[Date]) = #currentMonth
ORDER BY [Date], [Time];
or this:
SELECT [EnrolledID]
, [Date]
, [Time]
FROM dbo.view_attendance
WHERE DATEPART(year,[Date]) = datepart(YEAR,GETDATE()) And DATEPART(MONTH,[Date]) = datepart(MONTH,GETDATE())
ORDER BY [Date], [Time];
Related
Write a single query to search between two dates and when To date is not available then it should search greater then first date.
For example: search between two dates, when both from and to dates are available
11-10-2015 to 11-10-2017
My query should also return result when To date is not available
For example: I want to write single query without any if and else
This code works and it is a single statement, as requested.
SELECT * from MyTable WHERE recordingdate BETWEEN COALESCE(#startdate,CAST('01/01/1753 00:00:00.000' AS DATETIME)) AND COALESCE(#enddate,CAST('12/31/9999 23:59:59.997' AS DATETIME))
If the start date is NULL, COALESCE will return the minimum date value, as defined by SQL Server. Otherwise, it returns the start date value sent in.
If the end date is NULL, COALESCE will return the maximum date value, as defined by SQL Server. Otherwise, it returns the end date sent in.
Feel free to turn the COALESCE statements for MIN and MAX possible dates into functions, as SQL Server does not have built-in functions for minimum and maximum possible dates.
Writing your code this way allows you to always execute a BETWEEN.
Try Thie below Logic
DECLARE #FromDt DATE='01/01/2017',#ToDate DATE = NULL
SELECT
*
FROM YourTable
WHERE FromDate > #FromDate
AND
(
#ToDate IS NULL
OR
(
#ToDate IS NOT NULL
AND
ToDate > #ToDate
)
)
declare #dt_from date = '20151011',
#dt_to date = '20171011' -- null
select *
from dbo.your_table
where date_field >= #dt_from and data <= isnull(#dt_to, '99990101');
I keep getting the following error when running my query and am having trouble finding a solution.
Conversion failed when converting date and/or time from character string.
select * from creditcard
where cast(left(expdate,2) + '/01/' + right(expdate,2) as date) < '08/01/17'
and paycode <> ''
All of the dates in the table look like this '07/17'
declare #myfakedate varchar(25) = '07/17'
declare #mydatestr varchar(25)
Select #mydatestr = stuff(#myfakedate,3,0,'/01')
select #mydatestr
will give you '07/01/17'
If 2012+ user try_convert() just in case you have bogus data. Otherwise, the standard convert() should do
Example
Select *
From YourTable
Where try_convert(date,replace(expdate,'/','/01/'))<'08/01/17'
I am trying to automate the task using SQL server agent to generate the report of the people who gets inserted to the table on regular basis. I have created the below stored procedure, and was trying to use same query in SQL server agent job but is not working can someone please help.
SELECT s.LAST_NAME AS sn,
RTRIM(s.FIRST_NAME)+ ' ' + LTRIM(s.LAST_NAME) AS Name,
s.FIRST_NAME AS F_Name
LEFT(middle_name,1) AS Initial,
sy.USERNAME AS USER,
s.HOME_ZIP AS ZIP,
RTRIM(UPPER(sy.USERNAME)) + LTRIM('#xyz.com') AS userP,
stm.DESCRIPTION_Maj AS company,
rg.RECORD_INPUT_DATE
FROM STCIO s
JOIN SYSME sy
ON s.ID_NUMBER =sy.ID_NUMBER
JOIN EHMGR rg
ON s.ID_NUMBER =rg.ID_NUMBER
JOIN STMEER stm
ON rg.MAJOR =stm.MAJOR
AND s.MAT_CODE IN ('','G','Q')
AND rg.CURRENT_FLAG = 'X'
AND CONVERT(datetime,CONVERT(CHAR(8),rg.RECORD_INPUT_DATE)) = GETDATE()
NOTE:datatype for Record_input_date is numeric(8,0)
Error message received is
"Arithmetic overflow error converting expression to data type datetime."
I don't have an authority to make any changes. All I'm looking for is to have this query running converting the record_input_date (numeric) to datetime and populate the record based on the getdate()
Now this would happen if you still have the date stored as numeric in a wrong format (non ANSI format)
Like instead of 20160307 for today's date it stores it as 20160703 in which case it will give error for values like 20162002 or when the date is stored as ddmmyyyy or any other variant format. To solve look at some sample data and tweak your query from
CONVERT(datetime,convert(char(8),rg.RECORD_INPUT_DATE)) = GETDATE()
to
CONVERT(datetime,convert(char(8),rg.RECORD_INPUT_DATE),<formatstring>) = GETDATE()
See list of format strings here
Another way is to use date from parts function in higher version of sql server like
SELECT DATEFROMPARTS(RECORD_INPUT_DATE / 10000,
RECORD_INPUT_DATE % 100,
(RECORD_INPUT_DATE/ 100) % 100) AS YR_MNTH_DT
If you cannot use either of above, you'll have to isolate days,months and year from the number.
Example if your number is wrong format like ddmmyyyy (03062016)
DECLARE #dd INT, #mm INT, #yyyy INT, #newdate INT
SET #dd= RECORD_INPUT_DATE/1000000 --3
SET #mm= (RECORD_INPUT_DATE/10000) %100--6
SET #yyyy= (RECORD_INPUT_DATE) % 10000--2016
SET #newdate= #yyyy*10000+#mm*100+#dd
and use this #newdate for comparison
CONVERT(datetime,convert(char(8),#newdate)) = GETDATE()
Step 1 is turning this wall of text query into something you can read.
SELECT s.LAST_NAME AS sn
, RTRIM(s.FIRST_NAME) + ' ' + LTRIM(s.LAST_NAME) AS Name
, s.FIRST_NAME AS F_Name
, LEFT(middle_name, 1)AS Initial
, sy.USERNAME AS [USER]
, s.HOME_ZIP AS ZIP
, RTRIM(UPPER(sy.USERNAME)) + '#xyz.com' AS userP
, stm.DESCRIPTION_Maj AS company
, rg.RECORD_INPUT_DATE
FROM STCIO s
JOIN SYSME sy ON s.ID_NUMBER = sy.ID_NUMBER
JOIN EHMGR rg ON s.ID_NUMBER = rg.ID_NUMBER
JOIN STMEER stm ON rg.MAJOR = stm.MAJOR
AND s.MAT_CODE in ('', 'G', 'Q')
AND rg.CURRENT_FLAG = 'X'
AND CONVERT(DATETIME, CONVERT(CHAR(8), rg.RECORD_INPUT_DATE)) = GETDATE()
The problem here is that you have an integer that is not able to be converted to a datetime value. This is an inherent problem of using improper datatypes. You are likely going to be forced to drop the date condition from this query and replace it with an ISDATE. Insert those results to a temp table. Then another query to pull from the temp table with your date predicates.
I am trying to get data after year 2012.
Date is saved in nvarchar format in a table. For example: 12/31/2010
Column also has some other values like 'Confidential', I don't want this row.
I am trying a query (shown below) but it is not succeed :-
select *
from tbl_ProductionWells
where CONVERT(NVARCHAR(10), wellstatusdate, 103) > CONVERT(NVARCHAR(10), '01/01/2012', 103)
Edited :-
I tried this :-
SELECT *
FROM tbl_ProductionWells
WHERE DATEPART(YEAR, CAST(wellstatusdate AS date)) > 2012
But it is giving an error (shown below), This column also has some text values like 'not available','Confidential' .. :-
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
Note:- I can't change column datatype as it also contains some other texts.
Thanks in advance
First of all: Store date values in DATE columns, datetimes in DATETIME2 columns. Always choose proper data type for your data
You have to convert your NVARCHAR to DATE, then compare it to 2012-01-01
OR you can extract the 'year' part of your string.
SELECT *
FROM tbl_ProductionWells
WHERE CONVERT(DATE, wellstatusdate) >= '2012-01-01'
The best choice is to change your column's data type to DATE. After that, you can do lots of magicial things with those values. Store the 'Confidental' flag in another column.
EDIT
Some additional info:
Please note, that the STRING -> DATE conversion depends on the current session's language.
Run this batch to see the difference:
DECLARE #DateAsChar VARCHAR(32) = '01/02/12';
SET LANGUAGE us_english
SELECT CONVERT(VARCHAR(32), CONVERT(DATE, #DateAsChar), 120)
SET LANGUAGE Hungarian
SELECT CONVERT(VARCHAR(32), CONVERT(DATE, #DateAsChar), 120)
SET LANGUAGE Deutsch
SELECT CONVERT(VARCHAR(32), CONVERT(DATE, #DateAsChar), 120)
How about:
WITH cte
AS ( SELECT *
FROM tbl_ProductionWells
WHERE ISDATE(wellstatusdate) = 1
)
SELECT *
FROM cte
WHERE DATEPART(YEAR, CAST(wellstatusdate AS DATE)) > 2012
Select all data from the table that is a date using IsDate, then work with that dataset only.
SELECT * FROM
(SELECT * FROM tbl_ProductionWells WHERE ISDATE(wellstatusdate) = 1)
WHERE CAST(wellstatusdate as Date) > #YOURDATE
I want to convert a varchar value that iI set up to a date time value. I want to load rows of a database into another database, but conversion is not going well.
This is my query:
select Krant
, cast(jaar as varchar(4))+'-'
+RIGHT('0'+cast(maand as varchar(2)),2)+'-'
+RIGHT('0'+cast(dag as varchar(2)),2) as datum
, Inhoud as artikel
, LEN(Inhoud)-LEN(Replace(Inhoud,' ','')) as numwords
, 'Goirle' as vestiging
from [Sitecore_Bibliotheekmb_Krantenknipsel].[dbo].[KRANGOI]
The cast to Datum has to be a datetime value, but i am not getting it to work properly. When i tried to cast to datetime it gave me an out of range exception.
These are the results of this query:
alt text http://94.100.115.48/837450001-837500000/837478801-837478900/837478868_5_dE_7.jpeg
I want the "Datum" field to be a Datetime field with the same values but in Datetime format. Could anyone help me please :).
Thanks,
Younes
Use this:
select Krant, cast(cast(jaar as varchar(4))+'-'
+RIGHT('0'+cast(maand as varchar(2)),2)+'-'
+RIGHT('0'+cast(dag as varchar(2)),2) as datetime) as datum,
Inhoud as artikel,
LEN(Inhoud)-LEN(Replace(Inhoud,' ','')) as numwords,
'Goirle' as vestiging
from [Sitecore_Bibliotheekmb_Krantenknipsel].[dbo].[KRANGOI]
You are not casting the Varchars to a Datetime
CAST and CONVERT on MSDN.
Can you try this:
SELECT CAST(('2010' + '-' + '01' + '-' + '06') AS DATETIME)
If any of your dates are earlier than 1753, a simple datetime type will not be sufficient. For this, you'd need to use the datetime2 datatype introduced in SQL Server 2008.
Also check that all values of maand and dag are valid days and months.