Can't convert Datetime to Int - sql

I am trying to SELECT rows based on two values with this stored procedure:
ALTER PROCEDURE [dbo].[MYSelect]
-- Parameters with default values
#MitarbeiterId AS int,
#Wann AS datetime2(7)
AS
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SELECT *
FROM [Plan]
WHERE RefMitarbeiterId = #MitarbeiterId
AND Jahr <= YEAR(#Wann)
AND Monat <= MONTH(#Wann)
AND Abgeschlossen = 0
The problem is the following part:
AND Jahr <= YEAR(#Wann)
AND Monat <= MONTH(#Wann)
I don't know why this part is causing a (syntax) problem. With this lines included, using MSSQL Studio, I receive an error unable to convert DateTime to Integer. Removing these returns results and has no syntax error. I use YEAR() and MONTH() elsewhere, so I'm confused why there is a problem here.
This is the Plan table:

The conditions
AND Jahr <= YEAR(#Wann)
AND Monat <= MONTH(#Wann)
separate the condition to year and month.
It doesn't mean where the years and month are less then the parameter but where year is less or equal than the year of the parameter and the month is less or equal than the month of the parameter.
Using today (2014-06-30) as parameter your query will return every row where with Monat between 1 and 6 for the past and current year: the rows from December 2013, for example, will not be returned.
To get all the rows before the date of the parameter you'll need to change the conditions to
AND ((Jahr = YEAR(#Wann) AND Monat <= MONTH(#Wann))
OR Jahr < YEAR(#Wann))

After testing different ways of running this Procedure,
i now think its a bug if you use the View with a Datetime Parameter in SQL Server Manangement Studio
because i tested
EXEC
which works well
then removed my parameters
this returns an error which tells me that it was unable to convert '01.07.2014 00:00:00' to a datetime but it returns the right Rows
if i now do it again with my parameters and add my values
i get an exception which tells me the same think like the error above so i have to remove the ' and then i get the unable to convert DateTime to Integer which it's a bug in my opinion

Related

SQL query based on two values in a column with a date range

So here is what I'm attempting to accomplish. I want to have returned all rows within a specified date range where the value in a column is one value 'C' or another 'X'. I'm not huge in SQL and much more comfortable in scriptwriting for excel or google sheets. I would assume there's a pretty simple solution but here is what I have written so far that's not working.
Declare #FromDate DateTime
Declare #ToDate DateTime
Set #FromDate='20201027'
Set #ToDAte ='20201102'
select * from oehdr where OrderStatus='C' or OrderStatus='X'
The errors I've received have been "Invalid SQL, No Memory" and a script error when I modify the current attempt.
There's not enough info in the question. We don't know the name of the date column, or whether the time is included, or whether the ToDate value is inclusive of the whole day. It's not even 100% clear exactly what DB you're using, as there's some conflicting info with the question.
But I'll do the best I can making some guessues:
Declare #FromDate DateTime = '20201027'
Declare #ToDate DateTime = '20201102'
SELECT *
FROM oehdr
WHERE OrderStatus IN ('C', 'X')
AND OrderDate >= #FromDate AND OrderDate < DATEADD(day, 1, #ToDate)
Notice I did not use the BETWEEN operator. BETWEEN is inclusive at both ends of the range, which is rarely what I want for dates. Instead, when I want the full day, I add one day and use an exclusive condition for the end of the range.

SQL Server end of month

Suppose there is one date in int format 20191229, I want to find end of month and check if it's end of month is of 31 days or 30 days in SQL Server
You can try this from the reference. The given answer will not work for the integer data type but it will work in the varchar datatype date value. Storing Date values in integer is not a good idea, so as suggested by Larnu change the data type in either date or varchar.
SELECT
Day(EOMONTH(Cast('20191229' as Date))) end_of_month;
If you want the amount of days within a month, as you need the days as an integer, you should go for this. This is the most robust built, but also the more complex one, as to make sure the Integer value is processed correctly:
SELECT DATEPART(DAY,EOMONTH(CAST(CAST('20191229' AS NCHAR(8)) AS DATE))) AS Days
Result:
Days
31
If you want to add an IF evaluation to your selected date(s), you can do this by add an IIF-clause where it evaluates whether or not the end of month is 31 or not. If you want to use a columnname instead of the date, just substitute #Date with the columnname. I've just added the variable #Date instead of '20191229' to make it more illustrative/understandable. You can change the True/false descriptions to whatever you like in the query.
DECLARE #Date AS int
SET #Date = '20191229'
SELECT
IIF (
DATEPART(DAY,EOMONTH(CAST(CAST(#Date AS NCHAR(8)) AS DATE))) = '31'
,'True'
,'False'
) AS Days
Output:
Days
True

Query Datetime Declaration

I'm having trouble with a Datetime column in a table while adding declaration on a stored procedure.
I want to set #EventTime as a day of the week without modifying the column..
More like a catch.
For example:
declare #EventTime datetime
set #EventTime = (select EventTime
from _LogClients
where ClientID = #ClientID)
if (#EventTime like '%2-2%) -- As a day of a week not as a numerical date.
- - Datetime preview:2019-01-22 17:47:00
Any help regarding that matter?
Note:
The EventTime is used on a Stored Procedure which runs on a certain event that occur.. However, the database is a Game one, so the logger is based on the server files, I need to know if I'm able to make the EventTime declaration able to read the datetime from the column as weekday in order to execute a certain query for that day (Not SQL Agent based though.. that's a different story).
I'm not sure from your question if you are trying to get the numerical representation of the actual day of the week (like Sunday would be "1", Monday as "2", etc.. ) or if you just need the day of the week as a word from a date.
Here is your code modified to use the word for the day of the week (please note you could have used the DateName within the select statement but then you'd need to change the type of #EventTime to a nVarchar() or nchar) :
declare #EventTime datetime
set #EventTime = (select EventTime
from _LogClients
where ClientID = #ClientID)
if (DATENAME(dw,#EventTime) like '%Tuesday%)
If you wanted the numerical equivalent use:
if (DATEPART(dw,#EventTime) = '1' -- Testing for Sunday day name

Is there a way to persist dateparts Week and DayOfWeek in computed column?

To speed and simplify aggregation of data queries for a dashboard, I have added these additional date columns as computed columns derived from a date field when the record is inserted.
These 3 are created from (CONVERT([varchar],[DateCreated], (112))) or a substring of such. Persisting works. No problem.
YearUTC
YearMonthUTC
YearMonthDayUTC
However, with these 2, I receive the error
Cannot be persisted because the column is non-deterministic.
WEEK(DATEPART(WEEK, [DateCreated]))
DAYOFWEEK(DATEPART(WEEKDAY, [DateCreated]))
If cannot persist, I'm afraid the cost would be too great with large table (500K rows). Is there a work-around?
EIDT: Sorry, I was not using GetDate() in my real code. I should have changed that to a standard field, [DateCreated]. I updated my code above. Even with a standard date field that is known when the record is created, I get the same error.
Ok, I found a solution to the Week datepart. Use (datepart, ISO_WEEK, [datefield]) instead of (datepart, week, [datefield]) and you can persist the value. One more reason to hate on the nuances of time however, “The numbering systems of different countries/regions might not comply with the ISO standard.”
https://learn.microsoft.com/en-us/sql/t-sql/functions/datepart-transact-sql?view=sql-server-2017
The solution I went with for the DayOfWeek was to create an after update trigger as suggested by #Jeroen_Mostert
Now that you have the week part sorted, you can also create a (much simpler than it would be for the week) function for the weekday bit:
-- Monday is always 1 and so on
create function WeekdayAbsolute(#d datetime)
returns int
with schemabinding, returns null on null input
as
begin
declare #b int;
-- The zero date (i.e. cast(0 as datetime)) was Monday. Therefore...
set #b = 1 + ((datediff(d, #d - #d, #d)) % 7);
if #b > 7 set #b = #b - 7;
return #b;
end;
and use it in the column expression.

Concatenate two date parts

I'm trying to build a report based on a ticketing system we use. I'm quite new to SQL and just getting my head around it but the issue I am facing at the moment is trying to join two fields into a date. The data in the table is in displayed as Month_Number and Year_Number
I need to do a comparison with a datetime field to see if it is between the date range. I've searched a fair bit about concatenating the two fields I have into a date but unfortunately have come up short.
You can simply do this to concatination for youe Month & Date Part.
declare #month varchar(10);
declare #year varchar(10)
set #month = 5
set #year = 2014
You can choose whatever you feel for you is the best
select #month+'-1-' +#year as Your_Date
select '1-'+#month+'-' +#year as Your_Date
select #year+'-'+#month+'-1' as Your_Date
Output
5-1-2014
1-5-2014
2014-5-1
To Retrieve the date from your Table in SQL you can do like this
select month_number+'-1-' +year_number as Your_Date
from table_name
If you want to change the style of the displaying output then you can use Convert Function