C# search on date between Start and End date from database [duplicate] - c#

I am working on a website in asp.net. I am getting a date from a web page and then depending on the user input I want to get results from SQL Server database (using stored procedures).
Problem is that I am getting date only from UI in this format 2016-10-08 which is of type string. But in the database, I have a column which is of type datetime in this format 2016-10-08 17:38:00.000.
I am using this query to search but it does not work.
select *
from table
where acceptedDate like #sDate+ '%';
where sDate is input parameter for stored procedure. Please help. thanks

Don't pass dates as strings. Pass them as DateTime.
The .Net DateTime maps directly to SQL Server's DateTime. All you have to do is parse the string to a DateTime struct in your .Net code and pass it as a parameter to your stored procedure.
To search for a specific date and ignore the Time portion of the DateTime, better use >= and < in your sql:
select *
from table
where acceptedDate >= #Date
AND acceptedDate < DATEADD(DAY, 1, #Date);

If you only want compare with day level and ignoring the hours part, you can use DateDiff function.
Pass d or DAY to interval parameter of DateDiff
For example:
DECLARE #sDate VARCHAR(100)='2016-10-08'
IF ISDATE(#sDate)=1
BEGIN
select *
from table
where datediff(d,acceptedDate,#sDate)=0 --same day
END
ELSE
PRINT 'Invalid date format!'

Related

SQL stored procedure to pass date value in months/years

I am working on a C#/WPF application and connecting it with SQL.
I am trying to write a stored procedure in SQL that takes a selected date and converts it into (month, year) so at the time of executing, for example I put 1 for January and 2018 for the year and it will display the total sales for 2018 (that occurred in any given month in this case, January)
Ultimately in C#, the user will choose any given month from a comboBox, same for the year and click show sales and it should display using the stored procedure.
So far, I have this in SQL
ALTER PROCEDURE [dbo].[salesForSelectedMonth]
-- Add the parameters for the stored procedure here
#date date
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT SUM (TotalPrice) AS TOTAL_SALES, YEAR([TruckRental-PB].RentDate) AS year, MONTH([TruckRental-PB].RentDate) AS month
FROM [TruckRental-PB]
WHERE MONTH(#date) = MONTH([TruckRental-PB].RentDate)
AND YEAR(#date) = YEAR([TruckRental-PB].RentDate)
GROUP BY [TruckRental-PB].RentDate;
END
The issue is this is only allowing for putting a date then it shows the total sale
what I want is to get from C# the month (data type int), year (int) pass it to SQL proc to produce total sales
This is the logic I have so far (getting a datepicker value and passing it to the above proc) but getting an error still
public static int monthlySales (DateTime date)
{
using (Data_Context ctx = new Data_Context())
{
int sales = int.Parse(ctx.TruckRentalPbs.FromSqlRaw("salesForSelectedMonth", date).FirstOrDefault().ToString());
return sales;
}
System.InvalidOperationException: ''FromSqlRaw' or
'FromSqlInterpolated' was called with non-composable SQL and with a
query composing over it. Consider calling 'AsEnumerable' after the
method to perform the composition on the client side.'
UPDATE
I was able to pass month and year as int inside stored procedure however now it is showing the year as 1905 - any idea why?
-- Fetch matching month and year only
WHERE
#month = MONTH([TruckRental-PB].RentDate)
AND
#year = YEAR([TruckRental-PB].RentDate)
GROUP BY YEAR([TruckRental-PB].RentDate), MONTH([TruckRental-PB].RentDate)
Outcome
Your problem isn't really related to the type of parameter you pass, at least not your first problem. Your code
int sales = int.Parse(ctx.TruckRentalPbs.FromSqlRaw("salesForSelectedMonth", date).FirstOrDefault().ToString());
can't work this way. Entity Framework needs to map the result from FromSqlRaw to the entities it knows. But here you are returning an unknown result set where it doesn't know anything about its structure.
The workaround for this is to turn the result from EF into a memory bound collection and then use regular LINQ queries for the remaining code:
int sales = int.Parse(ctx.TruckRentalPbs.FromSqlRaw("salesForSelectedMonth", date).AsEnumerable().FirstOrDefault().ToString());
Then you can change the parameters by replacing the date parameter with two INT parameters and pass both into the query.

Stored procedure adds time to date format

I am using SQL server and stored procedures and I want to do a simple SELECT.
In my table I have a DATE format, which shows correctly in the database as yy-mm-dd.
When I call the stored procedure in my C# app, I also get a time value for every row (11/14/1987 12:00:00 AM).
How can I remove the time format?
Here is my select stored procedure:
ALTER procedure [dbo].[Employee_GetAllEmployees]
AS
BEGIN
SELECT * FROM
dbo.Employee
END
If you want only date then use convert() :
SELECT emp.*, CONVERT(DATE, date_col) AS New_date
FROM dbo.Employee emp;
The SQL Server date data type maps to .NET DateTime, which includes a time component. For formatting purposes in your application, use ToString according to your desired display format.
var formattedDateString = dateTypeField.ToString("yyyy-MM-dd");
Although you can format the value in T-SQL and return a string instead, burdening the database server for presentation formatting limits performance and scalability and is not considered a best practice.

Descending Order By Month SQL when date type is varchar using C# csharp

I have a column where date format is MM/yyyy stored in a varchar data type. Now I want to order it descending by MM/yyyy. How it is possible...
I have tried converted, str_date but failed...
You can use string functions for the ordering. Most databases support left() and right():
order by right(mmyyyy, 4), left(mmyyyy, 2)
However, you should fix your data model so the value is stored as a bona fide date, say the first day of the month.

SQL query returning timestamp attached with a date only column

I am trying to get date from a column which has its datatype set as date and in SQL Server the column also contains only date but when i run query from my application C#:
resultData[i][3] = sqlRdr["addedOn"].ToString();
It gives me a default time signature attached to it
select addedOn from sitrep;
I also tried using below cast but still same results:
select Convert(Date, Convert(datetime, addedOn)) as addedOn from sitrep;
If your saving it to a string i would try.
Convert.ToDateTime(sqlRdr["addedOn"]).ToShortDateString();
You can modify your query as:
resultData[i][3] = sqlRdr["addedOn"].ToString("M/d/yyyy");

How do I automatically get date when I create a new row in my SQL table?

I am doing a project in school, I have to create a website tool for salesmen to fill what they have done during the day, i.e. amount of quotes, quote sum, orders, order sum etc. I am using Visual Studio 2010, ASP.NET with C# with a SQL database.
I have to create a table with different columns, that I know how. But what I need is to have a column called Date and it has the datatype date. I need it to be filled automatically without having to input it manually. The same date that the new information was added. I have searched for solution in google and other places but I think I am searching with the wrong keywords, hopefully you can help me.
The format I wish for the date to be is DD-MM-YYYY
When you look for SQL default date on Google, the second result you get is this one.
In there, you have a default date example:
CREATE TABLE Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
OrderDate date DEFAULT GETDATE()
)
using the DEFAULT keyword.
Create a sql datetime column in the database, and specify a default value of GetDate() or GetUtcDate() depending on which you want. Format is irrelevant on the input side; you will have to use a formatter on the select side (or in your c# code).
You can set the default value for the column as current date time..
create table tblname (
fieldname datetime default getdate()
)
Also see this question
Add default value of datetime field in SQL Server to a timestamp
You can use one of this to insert in the table instead.
String s = System.DateTime.Now.ToString("dd.MM.yyyy");
DateTime now = System.DateTime.Now;
The second one would be your choice because the type specified in yur table is Date.
If don't want to be setting it from the app, specify which database you are using to get a specific answer.

Categories

Resources