The below query is giving error, please help me.
declare #dateScorecard datetime
set #dateScorecard = convert(varchar, 4)+'/1/'+ convert(varchar,2013)
select #dateScorecard
select top 1 i_CurrentMonthColor from AK_ScoreCardDetails scr
where datediff(m, convert(Datetime, convert(varchar, 4)+'/1/'+ convert(varchar,2013)), #dateScorecard)
error details:
Msg 4145, Level 15, State 1, Line 5
An expression of non-boolean type specified in a context where a condition is expected, near ')'.
Two quick comments:
First, you don't need to use convert on those numbers--just put them right into your query, i.e.
set #dateScoreCard = convert('4/1/2013');
Also, in the 'where' clause, you are not comparing the result of the datediff to anything There should be a section after the datediff clause, i.e.:
where datediff(.....) > 2
for example. Your datediff function only gives you a number that is the difference of the two dates you gave it, in the terms you define, which is months here. Use that number to compare to some value you want to make your sql statement work for you.
Related
I have a stored procedure that calls a linked server like below. The column 'datestr' is of type char(8) and is not always properly formatted. It is usually yyyymmdd but since I do not control how that data is formatted, I am using the TRY_CAST to only get rows where I can format it into a date.
Executing the SP gives me the following error:
Msg 242, Level 16, State 3, Line 1
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
Running the exact same code extracted from the SP in T-SQL returns data without error. I'm certain the issue is with the part of the WHERE clause with the DATEADD function hitting a value that is not able to be CAST into a date but I can't figure out why it runs differently in SP and extracted T-SQL.
I checked the plan using SET SHOWPLAN_ALL ON before running both and see some variations. Namely the estimated rows in the working query are much lower in the Remote Query operator (~200K vs. 15 mil)
CREATE Procedure [dbo].[SampleSP]
AS
SELECT top 50 tbl1.rowID as rowID,
year(datestr) as [year],
month(datestr) as [month],
count(*) AS CountRow
FROM [LinkedSer].[RemoteDB].[dbo].[tbl1] tbl1
inner join [dbo].[LocalTbl] tbl2 on tbl1.rowID = tbl2.rowID
WHERE tbl1.row_type = 'tbl1A'
and (TRY_CAST(tbl1.datestr AS date) IS NOT NULL
and tbl1.datestr > DATEADD(yy, -10, getdate()))
group BY tbl1.rowID, year(tbl1.datestr), month(tbl1.datestr)
The order the predicates are evaluated is plan-dependent. So you need to eliminate the potentially-invalid comparison from your code.
And simplifying to:
and TRY_CAST(tbl1.datestr AS date) > DATEADD(yy, -10, getdate())
should do the trick.
I am getting the SQL compilation error: syntax error line 1 at position 8 unexpected '-'.
sql query is :
INSERT INTO table_name(col_names) values();
position 8 is I of "INTO"
I am stuck with this tried searching the character from notepad++, but couldn't find.
You example of "it breaks" need to be reproducible. So you need to paste you not-working code (which is clear you don't want to) or toy sql that has the problem. It should look like:
create table toy_example(col_names text);
-- this works yippie!
insert into toy_example(col_names) values ('this is a value');
-- but this
insert into toy_example(col_names) values ();
/*
Syntax error: unexpected ')'. (line 22)
*/
because as it stands:
I have some SQL it gives me a error
002020 (21S01): SQL compilation error:
Insert value list does not match column list expecting 3 but got 1
my code looks like:
SELECT 1;
cannot really be worked with.
From your toy example your list of columns doesn't match the number of columns in your values clause. You're trying to insert 0 values into some number of columns.
You need something like
INSERT INTO table_name(col_1, col_2, col_3) values(1, 'hello', 'world');
I'm getting a similar, less than helpful error when I try something similar to your code. I think the parser is simply not able to comprehend a values clause with no input, so it's not even managing to figure out where the issue is, and it's just giving a generic "there's something wrong with your insert" error.
Thanks, #David Garrison and #Simeon Pilgrim for the time you put into answering my question.
The cause of my error was: I was using a Postgres data type: INTERVAL in my subquery with hyphen in it.
select CAST((DATE_TRUNC('MONTH', CURRENT_DATE) + INTERVAL '1 MONTH - 1 DAY') AS -
DATE
so , snowflake was not compatible with the hyphen above, but it was not showing the error in the correct line number while compiling the SQL instead it was showing the error in the first line INSERT INTO as explained in my question.(I think its a bug in snowflake)
So to make it compatible in snowflake , I used :
select CAST(LAST_DAY((DATE_TRUNC('MONTH', CURRENT_DATE))) AS DATE);
INTERVAL will work in snowflake but without hyphen, that is : INTERVAL '30 DAYS',
but this is not fair with the month of February, so I used LAST_DAY function.
and the query went fine :D
I am using the following query to retrieve snapshot values from 4 different dates: -1 day (latest), -2 days, -3 days and -40 days (not yet implemented).
SELECT [SnapshotDate]
,[SnapshotKey]
,[info1]
,[info2]
,[info3]
FROM [Database].[dbo].[Values]
WHERE [SnapshotDate] >= DATEADD(day,-3, GETDATE())
AND [SnapshotKey] = 'Some text here'
This results in the following graph:
The query is not quite right firstly since it is showing 4 values and should only be showing 3 at this point. Secondly I would like to show the last snapshot from 40 days ago as shown in the graph.
I have tried a few different queries but have not managed to figure out how to do this properly.
[SnapshotKey] = SELECT DATEADD(day,-40,getdate())
The above query gives me the correct answer in theory. However, when I use this in my query there is no result. I believe this might be due to not having a date conversion or the fact that I'm using "day" in my query. I'm not sure.
Any suggestions?
EDIT:
I also tried using the following with no luck (no result):
CONVERT(date, [SnapshotDate]) = CONVERT(date, DATEADD(day,-40, GETDATE()))
I'm not sure what your date values are but I'm guessing this report was run on 2nd May.
If this is correct then you need to change the range to exclude where the difference in dates is zero. Personally I use DATEDIFF in situations like this as it's easier to visualise for me.
Try changing the where clause to something like this.
WHERE (DATEDIFF(day, getdate(),[SnapshotDate]) BETWEEN -3 AND -1
OR DATEDIFF(day, getdate(), [SnapshotDate]) = -40)
AND [SnapshotKey] = 'Some text here'
I need to query a database for some information and then store it into a .csv file in case the dispatch system goes down. I'm running into some issues with the select query as well as the output statement. Here is what I have:
SELECT cmpy, veh, driver, attendant, trainee, unit_code, startdate
FROM vehicle_schedule
WHERE startdate >= 2015-07-22
ORDER BY cmpy, veh
The error that I am getting is this:
Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the varchar value '2010-05-25' to data type int.
I'm not sure what is going on and exactly how to fix the issue. Also I can't get it to output to a file, I get the error: incorrect syntax near 'OUTPUT'
Any help would be amazing!
This is too long for a comment. You are missing single quotes for the date constant:
WHERE startdate >= '2015-07-22'
The error you are getting is because 2015-07-22 = 1986 (they hyphens are interpreted as minus signs), so the query is turned into:
WHERE startdate >= 1986
Because of the comparison to an integer, SQL Server attempts to convert startdate to an integer . . . and you get a relatively unintelligible error.
you missed quotes around the date
try this
SELECT cmpy, veh, driver, attendant, trainee, unit_code, startdate
FROM vehicle_schedule
WHERE startdate >= '2015-07-22'
ORDER BY cmpy, veh
I am trying to us the DateAdd function of SQL in my Query. The problem is when I use a parameter to set the second arguement, the number argument I get an error which will say something like this:
Failed to convert parameter value from
a Decimal to a DateTime
While if I enter it parameterless, i.e hardcode an Int, it works fine.
This works:
SELECT FieldOne, DateField
FROM Table
WHERE (DateField> DATEADD(day, -10, GETDATE()))
while this does not:
SELECT FieldOne, DateField
FROM Table
WHERE (DateField> DATEADD(day, #days, GETDATE()))
Where #days = -10
Any ideas into what I am doing wrong? Incidentally I am setting this variable in SQL Server Manager, as I am trying to work out a bug in my DataAccess code. Not sure if that makes a difference.
Thanks
I know this is an old post, but for anyone else having this problem I had a similar issue in Reporting Services 2008 R2, although the error message was "Argument data type nvarchar is invalid for argument 2 of dateadd function." I think this issue could be related.
The problem was caused by the way Reporting Services parses the SQL code to generate a report dataset. In my case, I was able to change this dataset query:
SELECT DateAdd(wk, #NumWeeks, calendar_date) AS ToWeekFromDate
FROM dim_date
to this:
SELECT DateAdd(wk, Convert(Int, #NumWeeks), calendar_date) AS ToWeekFromDate
FROM dim_date
and the error was resolved.
EDIT: Just to expand on this answer a little: the issue was that Reporting Services was unable to parse the correct data type for #NumWeeks, I think possibly due to it being inside the DateAdd() function, and was defaulting it to NVarchar. Adding an explicit Convert() to set the data type to Int (even though it was already a number) enabled the parser to correctly identify the data type for #NumWeeks.
It sounds like you're passing the decimal as the 3rd instead of the 2nd parameter to DATEADD(), like:
DATEADD(day, GETDATE(), #days)
Although the snippet in the question looks fine.
(For extra clarity, the snippet above is an error. This is the code that would generate the error from the question.)
The following code works perfectly fine here (SQL Server 2005, executed in Management Studio):
DECLARE #days decimal
SET #days = -10
SELECT DATEADD(day, #days, GETDATE())
as does the following
DECLARE #days decimal
SET #days = -10
SELECT * FROM myTable WHERE myDate > DATEADD(day, #days, GETDATE())
So, the problem must lie somewhere else...
Are you sure the error is associated with this statement? There are no decimals involved and if I try this it still works
DECLARE #days decimal (19,6)
SET #days = -10.3346
--result is actually irrelevant
IF CAST(40000.6 AS decimal (19,6)) > DATEADD(day, #days, GETDATE())
SELECT 'yes'
ELSE
SELECT 'no'
Even trying to cast -10 decimal to smalldatetime this gives a different error
SELECT CAST(CAST(-10 AS decimal (19,6)) AS smalldatetime)
Msg 8115, Level 16, State 2, Line 1
Arithmetic overflow error converting expression to data type smalldatetime.