I am using this command it is not fetching record.
my command
select * from policy_record_manual where (CONVERT(VARCHAR(MAX), enddate, 103) BETWEEN CONVERT(VARCHAR(MAX), '25/02/2015', 103) AND CONVERT(VARCHAR(MAX), '04/03/2015', 103))
I have two records in enddate column which lies between 25/02/2015 and 04/03/2015 but still not fetching any result.
please help
Use proper date formats and your query should work:
select *
from policy_record_manual
where enddate between '2015-02-05' and '2015-03-04'
You are doing the comparison as strings. Don't compare date/times as strings. Compare them using the native types.
You should always compare dates/datetimes with dates - and not strings. Most databases -- including SQL Server -- support the ISO standard for dates and recognize strings in that format.
If you use SQL Server, you can change the date format in the query by using SET DATEFORMAT statement.
set dateformat dmy
declare #begin datetime='25/02/2015'
declare #end datetime='04/03/2015'
select *
from policy_record_manual
where enddate between #begin and #end
try this
select *
from policy_record_manual
where (CONVERT(VARCHAR(MAX), enddate, 103) BETWEEN CONVERT(VARCHAR(MAX), '02/25/2015', 103) AND CONVERT(VARCHAR(MAX), '03/04/2015', 103))
Related
I have to compare a table field that is a date stored as varchar in the format 'dd/MM/yyyy' with a date value, but the comparison fails. I have exception
Conversion failed when converting date and/or time from character string.
I tried converting the date to compare i nstring, like this
string dateFormat = date.ToString("dd/MM/yyyy");
and then write the query like this:
string sql = "select * from TB_RICHIESTE where CONVERT(DATE, Date) <= CONVERT(DATE, '" + dateFormat + "')";
But I have this excpetion. Someone can help me? Thanks
First, you should not store dates as strings.
As Panagiotis Kanavos wrote in his comment - this is a serious bug. You can't sort by such a column, you can't search for date ranges, and most important - you can't control if someone enters an invalid value - nothing is stopping someone from entering "Alfredo" to that column.
For more information, read Aaron Bertrand's Bad habits to kick : choosing the wrong data type.
Second, you should not pass dates from .Net to Sql server as strings. you should pass instances of DateTime as parameters.
The .Net DateTime maps directly to SQL Server's Date.
If you can't change the data type of the column, you can at least convert it to date using the proper convert style (103 in your case).
Here is a better way to do it:
var sql = "select * from TB_RICHIESTE where CONVERT(DATE, [Date], 103) <= #Date";
Then you add the #Date parameter to the SqlCommand:
com.Parameters.Add("#Date", SqlDbType.Date).Value = date.Date;
Use Parameter to pass date values refer #Zohar Peled post. This is the proper method handling date values.
OR
You can pass the date value in ISO format, refer the below code.
string dateFormat = date.ToString("yyyy/MM/dd");
string sql = "select * from TB_RICHIESTE where CONVERT(DATE, Date) <= CONVERT(DATE, '" + dateFormat + "')";
I have an SQL Server Database, managed through SQL Server MS, interfacing with a c# application and i am struggling with a certain query.
The database is for a campsite booking system, which consists of the following tables relevant to the query.
BOOKING(BookingID, StaffID, CustomerID, PitchID, StartDate, EndDate)
PITCH(PitchID, TypeOfPitch, Capacity)
One pitch can occur in many bookings.
I am looking to create a query which will check the availability of a pitch on a certain date, which is input from a dateTimePicker. The query will return the available pitches and display them in a datagridview. Here is what i have so far.
SELECT * FROM dbo.PITCH, dbo.Booking
WHERE #Date
NOT BETWEEN dbo.BOOKING.[Start Date] AND dbo.BOOKING.[End Date]
This SQL code is not working, it is returning a pitch for every booking in the table.
All the c# around the SQL is working, i'm just not great at SQL queries and need some help!
Thanks in advance
SELECT * FROM dbo.PITCH
WHERE PitchID NOT IN
(
-- sub-query to take reserved pitches
select PitchID from dbo.Booking
where #Date BETWEEN [Start Date] AND [End Date]
)
The following should do what you want. The sub query pulls the pitches that are booked during the given date. So you want the pitches not in that query.
Select *
From dbo.PITCH
WHERE PitchID Not In (
select PitchID
from dbo.Booking
where #Date between [Start Date] And [End Date])
DECLARE #DATE DATETIME
SELECT
,b.BookingID
,b.StaffID
,b.CustomerID
,b.PitchID
,b.StartDate
,b.EndDate
,p.capacity
from Dbo.Pitch p
INNER JOIN Booking b ON b.PitchID = p.PitchID
WHERE #Date BETWEEN b.StartDate AND b.EndDate
ORDER BY #DATE DESC
Since you want the show the date picked from the PICKER at the top you need ORDER BY CLAUSE as well .
Get in the habit of writing like this as it will help you easily solve as well as analyse the problem .
HOPE IT HELPS
I need to retrieve only today's data from a SQL Server database table.
I am developing an application in C#, VS 2010 and there is need that to retrieve only today's data.
Not getting the exact query how should it be. Also need to retrieve that data order by Desc.
How can we do this?
Yoou have to take the Date_time Column in Your TABLE That will keep the information of time when your row entered in table.
SELECT Date_Time
FROM TableThantYouWantAcees
WHERE Date_Time = CONVERT(date, Getdate())
ORDER BY Date_Time DESC
GETDATE() is an SQLServer function which will return the today date, like 2013-11-20 14:05:54.943. Cast it in DATE to only keep the date part, ie 2013-11-20.
Try this
SELECT * FROM <table_name>
WHERE <date_field> >= CONVERT(<date_field>,
DATEDIFF(DAY, 0, GETDATE()))ORDER BY <date_field> DESC
Extract the date part from your date_column with convert
select * from your_table
where CONVERT (DATE, date_column) = CONVERT (DATE, GETDATE())
order by date_column desc
If you are concerned about only having the date and not the time, you could so something like this:
SELECT *
FROM tblPhoneAsign
WHERE receivedTime > CAST(FLOOR(CAST(GETDATE() AS FLOAT))AS DATETIME)
That will give you only the date portion of today's date. Doing the adding of zero hours to the GETDATE method is a very complex and costly way of doing things.
My problem is that I want to select records from data base if the date field is greater than current date
I use the following code
SELECT
Id, eve_name, eve_date, eve_place,eve_desc
FROM
EventDetails
WHERE
CONVERT(varchar(10), eve_date, 101) >= CONVERT(varchar(10), " + DateTime.Now.ToShortDateString() + ",101)"
but it is not working
I take date column in database as DateTime.. and save the date time using jquery datetime picker
Assuming the server date is acceptable, and that this is SQL Server (it looks like it since you're using CONVERT), you can just do this in SQL:
SELECT
Id, eve_name, eve_date, eve_place,eve_desc
FROM
EventDetails
WHERE
eve_date >= DATEADD(day,DATEDIFF(day,0,CURRENT_TIMESTAMP),0)
And this can also use an index on eve_date, if one is available - because I'm no longer applying any functions to it. I'm using DATEADD/DATEDIFF to remove the time component from the current datetime (obtained via CURRENT_TIMESTAMP).
If you are using SQL Server, you can use the GETDATE() function. This returns the current date/time. If your date-time fields only contain a DATE part, you will need to strip the time part of the result of GETDATE().
SELECT
*
FROM
eventdetails
WHERE
eve_date>=CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME);
You will see that the time part is stripped of the result of GETDATE() by casting it to float, flooring it and casting it back to DATETIME type. There are other ways of doing this, cf Damien's solution. Since DATETIME under the hood is stored as a FLOAT, only one trivial function is called (FLOOR), and performs better than the DATEADD/DATEDIFF trick.
If the eve_date can also contain a TIME part, and you want to compare only the DATE part, you will also have to CAST/CONVERT the eve_date to make the comparison:
SELECT
*
FROM
eventdetails
WHERE
CAST(FLOOR(CAST(eve_date AS FLOAT)) AS DATETIME)>=CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME);
Now this is all written in the perspective of SQL Server 2005 and below, where a DATE type does not exist. For SQL Server 2008 and above, casting to the DATE type will strip the TIME part away as well:
SELECT
*
FROM
eventdetails
WHERE
CAST(eve_date AS DATE)>=CAST(GETDATE() AS DATE);
Note that the GETDATE function is the equivalent of CURRENT_TIMESTAMP function as defined by ANSI SQL standard.
Try this,
it is simple and fulfills your requirement
:-
Assuming you are using SQL SERVER
SELECT
Id, eve_name, eve_date, eve_place,eve_desc
FROM
EventDetails
WHERE
eve_date >= getdate()
Since in Database eve_date column type is Datetime ,so there should not be any problem.
Change datatype inside CONVERT to datetime from varchar
Try This SQL QUERY:
SELECT
Id, eve_name, eve_date, eve_place,eve_desc
FROM
EventDetails
WHERE
eve_date>= CONVERT(datetime, '#dtp',101)
C# code avaoiding SQL Injection:
try
{
cmd=new SqlCommand(SELECT Id, eve_name, eve_date, eve_place,eve_desc FROM EventDetails WHERE eve_date >= CONVERT(datetime, '#dtp',101),con);
da=new SqlDataAdapter(cmd);
cmd.Parameters.AddWithValue("#dtp", DateTime.Now.ToShortDateString());
ds=new DataSet();
da.fill(ds);
//Further Processing
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
This will work.
The Bill_Date is saved as a string in the database. Now I want to select the records based on this Bill_Date. So I input two dates ie. fromDate and toDate (which are also in string).
All the date values use the U.S. format mm/dd/yyyy (e.g. 11/28/2011).
So how will be the query?
Firstly, your life will be much easier (and the query much faster) if everything was a datetime.
The query (as it stands) would be:
SELECT *
FROM TABLE
WHERE CONVERT(datetime, BILL_Date, 101)
BETWEEN CONVERT(datetime, #fromDate, 101) AND CONVERT(datetime, #toDate, 101)
CONVERT is detailed here.
If the Strings are in the format YYYY-MM-DD (or any other format, where the dates would be chronologically ordered if you sort by the string) you can use between:
select * from table where Bill_date between fromDate and toDate
If a different date format is used you need to parse the strings and create dates, either in c# or in sql. In Oracle you would use TO_DATE, i assume there is something similar in SQL server.