Sql server get result of one month before - c#

I have the following query
DECLARE #StartDate DATETIME, #EndDate DATETIME
SET #StartDate = DATEADD(mm,-1, getdate())
select count(status) from [full]
where (date_reception> #StartDate and status = 'OPEN')
I need to get result of one month before now , for example we are in 2015-03-19 i need to get result from 2015-02-19 till now.
When i try query above i get as result (4412) and when i try (where date_reception >'2015-02-19') i get (5638)

If the time component of the date is not to be considered, try the following code. If it is, your current code seems accurate.
DECLARE #StartDate DATETIME, #EndDate DATETIME, #currentDate date
set #currentDate = GETDATE()
SET #StartDate = DATEADD(mm,-1, #currentDate))
select count(status) from [full]
where (date_reception> #StartDate and status = 'OPEN')

try
WHERE date_reception BETWEEN DATEADD(month, -1, GETDATE()) AND DATEADD(GETDATE())

Related

How can I get SQL data values according to machine name filtering?

When I tried to get specific data values of machine address I could not get values of this
ALTER PROCEDURE [dbo].[Datade]
#makineadı varchar,
#startdate datetime
AS
BEGIN
SET NOCOUNT ON;
SELECT *
FROM HMI.[dbo].Tarihmakine
WHERE MakineAdı = #makineadı
AND Tarih = #startdate
END
And I used this stored procedure inside of this API controller, normally when I tried to get desired date of the SQL data I can pull it but when I tried to string format of machine name I could not get data of this I think this caused of DOUBLE QUOTE but I could not convert it to single ''
public class RaporController : ApiController
{
public IHttpActionResult Getemprecords(string makineadı, DateTime? startdate)
{
HMIEntities1 sd = new HMIEntities1();
var results = sd.Data(makineadı, startdate).ToList();
return Ok(results);
}
}
I used this web page to get specific values https://localhost:44355/api/rapor?makineadı=192.168.0.8&&startdate=2021-01-29
Here is my database enter image description here
Your code looks like SQL Server. If so, never use string declarations without a length:
ALTER PROCEDURE [dbo].[Datade] (
#makineadı varchar(255),
#startdate datetime
) AS
BEGIN
SET NOCOUNT ON;
select *
from HMI.[dbo].Tarihmakine
where MakineAdı = #makineadı and Tarih = #startdate
END;
The default date also varies by context -- and these bugs can be very hard to debug. In your case, the default is varchar(1), which is not what you intend.
The other potential issue is the use of datetime for the second argument. However, what you want is not clear:
If you. Tarih is a date, then pass the argument in as a date.
If Tarih is a datetime and you want the values on the same date, then pass in a date and use convert(date, Tarih) = #startdate.
Only use the code as is if Tarih is a datetime (of some sort) and you want the comparison down to a fraction of a second.

SQL Server: Search values of type "varchar" with parameters of type "date"

I have a column "Uploaded" of type varchar(25). It has datetime values. Since the string stored in this column is not valid date(front-end is passing them. No control over there) it is kept as varchar(25). The strings stored in it are like:
2016:04:14 21:20:35
2016:04:14 21:20:35
2016:04:14 21:20:35
.
.
.
I need to compare these values in a search query
Select * from Table where [Uploaded] BETWEEN #StartDate AND #EndDate
#StartDate and #EndDate are date type variables. Obviously the above query won't work. So, I have 2 ways:
1. Write correct query that can compare the passed date type variables with the "Uploaded" column.
2. Update the [Uploaded] column values and re-store them as a valid datetime type.
How can that be achieved? Can someone help me writing either the correct search query or update all the records to convert them in valid datetime type?
If you got : between year, month and day in [Uploaded] field then use this:
SELECT *
FROM Table
WHERE CAST(REPLACE(LEFT([Uploaded],10),':','-') as date) BETWEEN #StartDate AND #EndDate
If datetime needed then:
SELECT *
FROM Table
WHERE CAST(REPLACE(LEFT([Uploaded],10),':','-') + RIGHT([Uploaded],9) as datetime) BETWEEN #StartDate AND #EndDate
This will give you accurate result.
select * from Table where cast(replace(left([Upholded],10),':','-')+right([Upholded],len([Upholded]-10) as datetime) between #StartDate AND #EndDate
you can cast the string data to a datetime value and then use datetime comparison
Select * from Table where CAST( [Uploaded] as Date) BETWEEN #StartDate AND #EndDate
make sure you use the right format for your datetime conversions and you should be golden.
here's some more info : https://msdn.microsoft.com/en-us/library/ms187819.aspx

Stored procedure with nullable value in date field

In this stored procedure , in a where condition if #startDate and #EndDate values are null then how it can be handle using COALESCE.
CREATE PROCEDURE dbo.SP_ManageLeaveSearch
#StartDate datetime,
#EndDate datetime,
#UserName CHAR(100),
#MarketID INT
AS
BEGIN
SELECT d1.UserName,c1.HouseName,c.StartDate,c.EndDate
FROM table1 c
Inner JOIN table2 d1 ON c.UserID = d1.UserID
WHERE
(
(
(#StartDate BETWEEN StartDate AND EndDate)
OR
(#EndDate BETWEEN StartDate AND EndDate)
OR
(
(#StartDate <= Startdate AND #EndDate>=EndDate)
)
)
AND
(
d1.UserName = COALESCE(#UserName, d1.UserName)
)
)
END
Thnaks in advance.
This should work for you:
CREATE PROCEDURE dbo.ManageLeaveSearch
#StartDate datetime = NULL,
#EndDate datetime = NULL,
#UserName CHAR(100) = NULL,
#MarketID INT
AS
BEGIN
SELECT d1.UserName,c1.HouseName,c.StartDate,c.EndDate
FROM table1 c
Inner JOIN table2 d1 ON c.UserID = d1.UserID
WHERE
COALESCE(#StartDate,StartDate) <= EndDate AND
StartDate <= COALESCE(#EndDate,EndDate) AND
d1.UserName = COALESCE(#UserName, d1.UserName)
END
Notes:
Don't name stored procedures with an sp_ prefix - it's reserved for Microsoft's system procedures.
I've gone with simpler conditions for determining an overlap exists. An overlap exists between two ranges if range 1 starts before range 2 ends, and range 2 starts before range 1 ends.
I've specified defaults for those parameters that should be nullable.
Try this one -
CREATE PROCEDURE dbo.usp_ManageLeaveSearch
#StartDate DATETIME,
#EndDate DATETIME,
#UserName CHAR(100),
#MarketID INT
AS BEGIN
SELECT
d1.UserName
, c.HouseName
, c.StartDate
, c.EndDate
FROM dbo.table1 c
JOIN dbo.table2 d1 ON c.UserID = d1.UserID
WHERE d1.UserName = ISNULL(#UserName, d1.UserName)
AND (
ISNULL(#StartDate, StartDate) BETWEEN StartDate AND EndDate
OR
ISNULL(#EndDate, EndDate) BETWEEN StartDate AND EndDate
)
END
You've overly complicated things. This should work for you, and is as simple of a query as I know of. I prefer this syntax because in most of my use cases, the ...OR #UserName IS NULL can be removed from the query before it is even executed thereby making a very simple, fast execution.
CREATE PROCEDURE dbo.SP_ManageLeaveSearch
#StartDate datetime,
#EndDate datetime,
#UserName CHAR(100),
#MarketID INT
AS
BEGIN
SELECT d1.UserName,c1.HouseName,c.StartDate,c.EndDate
FROM table1 c
JOIN table2 d1
ON c.UserID = d1.UserID
WHERE (#StartDate<=EndDate OR #StartDate IS NULL)
AND (#EndDate>=StartDate OR #EndDate IS NULL)
AND (d1.UserName = #UserName OR #UserName IS NULL)
END

Issue Related to Date Range in SQL Server

I have written following Query in SQL Server :
SELECT *
FROM AttendanceMaster
WHERE Date between '8/12/2012' AND '8/20/2012'
butt Query result returns '8/13/2012' AND '8/19/2012'
but it doesn't returns result for date 12/8/2012 and for date 8/20/2012
so what is the solution to get the data for above two date ?
Try with following query:
SELECT *
FROM AttendanceMaster
WHERE CAST(Date AS DATETIME)
BETWEEN DATEADD(DAY , -1 ,CAST('2012-08-12' AS DATETIME)) AND
DATEADD( DAY , 1 ,CAST('2012-08-20' AS DATETIME));
If you are using SQL Server 2008, you only need to do something like this:
SELECT *
FROM AttendanceMaster
WHERE CONVERT(DATE, [Date]) BETWEEN CAST('2012-08-12' AS DATE) AND CAST('2012-08-20' AS DATE)
EDIT: I am making 2 assumptions here.
1) That you have indeed confirmed that you have data in your AttendanceMaster table that has [Date] equal to 12th and/or 20th August 2012 - you dont want to look for something that is not even there in the first place ;)
2) That the [Date] column is most probably of DATETIME SQL Server type
its not TO but instead AND
select *
from AttendanceMaster
where Date between '8/12/2012' AND '8/20/2012'
try casting it to date
SELECT *
FROM AttendanceMaster
WHERE CAST([Date] AS DATE) BETWEEN CAST('2012-08-12' AS DATE) AND CAST('2012-08-20' AS DATE)
I would suggest you to use <, <=, >=, or > because they allow more flexibility than BETWEEN and you have the choice to including or exclude the endpoints.
So you can rewrite your query like this
SELECT *
FROM AttendanceMaster
WHERE Date > '8/12/2012 00:00:00' AND Date < '8/21/2012 00:00:00'
Plz note that in the above query the end date is 21st and not 20th.
Also remember that by default SQL Server will take any date like '8/20/2012' AS '8/20/2012 00:00:00' and therefore any datetime greater than this will not appear in result if you use BETWEEN or if you dont specify the exact time stamp.
Hope it helps.
If you give dates '2012-08-12' and '2012-08-20' then it returns the data between '2012-08-12 0:00 AM' and '2012-08-20 0:00 AM' So it does not return the valuesfrom the date '2012-08-12'. So you need to write the target date as '2012-08-21'
If you have the date '2012-08-20' in a variable for ex:
DECLARE #FromDate DATETIME
DECLARE #ToDate DATETIME
SET #FromDate = '2012-08-12'
SET #ToDate = '2012-08-20'
DECLARE #NextDate DATETIME
SET #NextDate=CAST(FLOOR(CAST(dateadd(day,1,#ToDate) AS FLOAT)) AS DATETIME)
/*This Returns the Next Day Date.*/
SELECT *
FROM AttendanceMaster
WHERE Date between #Date AND #NextDate
Or you can write as
DECLARE #FromDate DATETIME
DECLARE #ToDate DATETIME
SET #FromDate = '2012-08-12'
SET #ToDate = '2012-08-20'
SELECT *
FROM AttendanceMaster
WHERE Date between #Date AND CAST(FLOOR(CAST(dateadd(day,1,#ToDate) AS FLOAT)) AS DATETIME)

Linq-to-SQL date format: query does not work

I have a stored procedure when I am executing this query in SQL Server
exec SelectOfficeNameGroup '2011-10-05', '2011-11-09', ''
it returns 110 rows.
Now I have two datepicker on my c# 3.5 form and one button which executes the query like this:
var result = context.SelectOfficeNameGroup(dateTimePickerFrom.Value, dateTimePickerTo.Value, "");
but its only returns 2 rows.
My date picker's format is MM/DD/YYYY
This is my procedure
ALTER PROC [dbo].[SelectOfficeNameGroup]
#From datetime,
#To datetime,
#OfficeName nvarchar(50)
AS
BEGIN
SELECT
ID AS ProductID, OfficeName,
SUM(Quantity) AS Quantity,
SUM(TotalPrice) AS TotalPrice,
Category
FROM
ProductLogWithCategory
WHERE
DateTime BETWEEN #From AND #To AND OfficeName = #OfficeName
GROUP BY
OfficeName, ID, Category
return
END
Any advice?
Try with
var result = context.SelectOfficeNameGroup(dateTimePickerFrom.Value.ToString("yyyy-MM-dd"), dateTimePickerTo.Value.ToString("yyyy-MM-dd"), "");
Have a look at the DateTime.ToString documentation
Update
Just to be on the safe side try
ALTER PROC [dbo].[SelectOfficeNameGroup]
#From varchar(8),
#To varchar(8),
#OfficeName nvarchar(50)
AS
BEGIN
SELECT
ID AS ProductID, OfficeName,
SUM(Quantity) AS Quantity,
SUM(TotalPrice) AS TotalPrice,
Category
FROM
ProductLogWithCategory
WHERE
DateTime BETWEEN #From AND #To AND OfficeName = #OfficeName
GROUP BY
OfficeName, ID, Category
return
END
and use it like this
from sql
exec SelectOfficeNameGroup '20111005', '20111109', ''
from linq
var result = context.SelectOfficeNameGroup(dateTimePickerFrom.Value.ToString("yyyyMMdd"), dateTimePickerTo.Value.ToString("yyyyMMdd"), "");
DateTime.Parse('your date in MM/DD/YYYY', new CultureInfo("en-US")).ToString("yyyy-MM-dd")

Categories

Resources