I have month in an integer variable int month =DateTime.Now.Month; and I have Two dates in database they are '11/01/2014'and '11/30/2014' . Now I want to bring least and grater days in a string. how can I achieve it.(in database I have Fromdate('11/01/2014') and Todate('11/30/2014')fields)? I am new in this field.
There are Min and Max functions you can use to find this. The best way to use these is to ensure that you are first storing the date as a date or datetime value (or similar), as casting from one type to another can be an expensive operation.
Sample:
Select Min( MyDateColumn) as "MinDate", Max(MyDateColumn) as "MaxDate"
From MyTable;
If they are not stored as a form of date value, you will have to cast the value to a date. If it is stored as a varchar or char, for example, you will need to do this. If you don't, the min and max will be calculated based on the ascii values of characters, not on the actual dates.
Sample (avoid, if possible):
Select Min( CAST(MyDateColumn as date) ) as "MinDate",
Max( CAST(MyDateColumn as date) ) as "MaxDate"
From MyTable;
Related
I have dates stored in varchar column(bad idea i know) without date deperators.. in ddMMyyy format .. Example: 23-10-2013 is stored as 23102013 in database. Now i want to search for records between two particular dates such as 12-10-2013 and 20-10-2013 How do I come about this?
I am using SQL Server
Try this:
SELECT *,
LEFT(CONVERT(VARCHAR, t.[parseddate], 120), 10) AS ParsedDate2
FROM (SELECT *,
CONVERT(DATETIME, Stuff(Stuff([startdate], 3, 0, '-'), 6, 0, '-')
, 105)
AS
ParsedDate
FROM mytable) AS t
WHERE t.[parseddate] BETWEEN '2013/10/10' AND '2013/10/20'
You may see it working here.
For the available date and time styles, take a look at this MSDN article:
CAST and CONVERT (Transact-SQL).
I suggest you 3 solutions.
1-update your column add - eg:23052012 --> 23-05-2012 you can use substring to reach goal and then I will work fine with comparison operators.
Note it is work for just dd-mm-yyyy
2-use substring to separate first 2 digits as day and others then compare integers with variables.
3- convert(date,yourdate)
I had a table employeeswipe_tbl in SQL Server 2008 with these columns:
create employeeswipe_tbl swipepk int (
swipepk int primary ,
empid int,
dateofswipe date ,
intime datetime,
outime datetime,
logduration time
)
When employee login in the intime, empid, dateofswipe is entered and when log out the outime is updated against swipepk
Now what I want is when I update outtime the logduration will be automatically calculated like
logduration = outtime - intime
I am thinking of a some ideas like a computed column or a trigger. Can anyone give a good option considering I am a beginner ?
A computed column is usually a better option than a trigger. Triggers can be disabled. A computed column is "always" correct:
create table employeeswipe_tbl (
swipepk int primary key,
empid int,
intime datetime,
outime datetime,
dateofswipe AS CONVERT(date,intime) ,
logduration AS DATEDIFF(second,intime,outime)
)
As indicated in my comment, the difference between two datetimes would be a time span, not another datetime. There's no time span type in SQL Server, so just keeping the difference in seconds is probably best - do any formatting of it into hours, minutes and seconds during display. This will make it easier if you need to, for instance, add together several rows worth of data.
Side note - I was considering making dateofswipe a computed column also - isn't it just the date part of intime?
I have a variable which is datetime type. How can i get the shortdatetostring() as datetime variable type ? I have a column in databae as datetime type. I would like to get the records which are added at a certain day.
Example:
SELECT id FROM database WHERE added like #p1
The parameter of the query is a datetime variable.
Match based on day, month, and year of the date variables. Do not use strings, since matching is slow.
SELECT id
FROM database
WHERE Datepart(yy, added) = Datepart(yy, #p1)
AND Datepart(mm, added) = Datepart(mm, #p1)
AND Datepart(dd, added) = Datepart(dd, #p1)
You could do something like this in order to get all the ids on the 26th of January.
SELECT id FROM database WHERE added >= '2012-01-26' and added < '2012-01-27'
In C# you do like below.
DateTime dt;
string Temp1 = "Your Date";
if (DateTime.TryParse(Temp1, out dt))
{
// If it is a valid date
string date = dt.ToShortDateString();
string time = dt.ToShortTimeString();
}
In SQL Server
SELECT id FROM database WHERE Datepart(dd, added) = Datepart(dd, #p1)
Please see below the sample
create table #temp
(
dat datetime,
)
insert into #temp(dat)values(GETDATE())
insert into #temp(dat)values(GETDATE()+1)
insert into #temp(dat)values(GETDATE()+2)
select * from #temp where DATEPART(dd, dat) > 27
drop table #temp
If you are using parameterised queries the format of the datetime type doesn't matter.
Got to remember that "2012-01-26" is a string not a date....
If you need a Date formatted a particular way, then myDateTime.ToString(....), there are several overloads, one of which is simply a format String e.g. "yyyy-MM-dd"
If you want to parse a string into a datetime then DateTime.Parse(...), again there are several overloads.
More on dates after comment
DateTime.Parse("12/31/2012") gives you a datetime type in c#.
It parses the string into a DateTime
MyDateTime.ToString("MM/dd/yyyy") gives you a string of date in the specified format.
"31/12/2012" is not a date, if you want it as a date, then you Parse it into one.
Now which way do you want to go DateTime to a string, or string to a DateTime, or are you asking something completely different?
If you want to only Parse DateTimes trhat are in the format mm/dd/yyyy, you can't because when it's string there's absolutely no way to tell the 6th of August from the 8th of June, unless you assume the format is always mm/dd/yyyy which is pretty much guaranteed to go badly wrong at somepoint, which is why when going from Date to String YYYYMMDD or YYYY-MM-DD are the way to go.
If it's what you want / have to do then
DateTime MyDateTime = DateTime.Parse("12/31/2012",CultureInfo.CurrentCulture);
Pass a string in a format that doesn't fit the pattern and it will throw an exception, NB that would include "31/12/2012".
CultureInfo is in the System.Globalisation namespace.
There area number of options. Current, CurrentUI, Invariant etc. Which one you use depends on how you are setup and globalisation / internationalisation requirements (even if they are none). So using Current Culture, would assume US default regional settings. But if I was to run your code, then "31/12/2012" would work and "12/31/2012" would blow chunks.
If you want to fix the formats no matter what system they are run on then InvariantCulture is the way to go. Don't forget to set the neutral language as well. Hit the assembly button on the Applications tab of the project's property pages. Neutral language is a drop down near the bottom. Presumably you want en-us.
If you don't want the excpetion then it's
DateTime myDateTime;
if (DateTime.TryParse("12/31/2012",CultureInfo.CurrentCulture, out myDateTime)
{
// do something with myDateTime...
}
else
{
// do something about the value not being in the correct format
}
You might be able to simplify this by editing the query, actually. Try
select id from database where cast(added as date) = cast(#p1 as date)
This (effectively) strips the time from added as well as the time from #p1 and compares the dates only.
I need to sort by date but the date is stored as text in the database. I am using Linq to entities to perform queries.
The way the database is designed it is not feasible to change the column to a date column because many different data types are in that column. There is a descriminator column named type so I will know what type a particular row is.
You can add a computed column to the table that will convert those strings to dates when your discriminator has a specific value (here I've just used 'date').
ALTER TABLE Foo
ADD trueDate AS
CASE
WHEN type = 'date' THEN CONVERT(date, 'mixedColumn', 101)
ELSE NULL
END
PERSISTED
If you have time information, then date should be datetime in the CONVERT() function.
Also, the 101 is a style code indicating an expected format of MM/dd/yyyy. If you have something different, refer to this: http://msdn.microsoft.com/en-us/library/ms187928.aspx, but keep in mind that if you use a style below 100 your expression will be considered non-deterministic and you cannot make your computed column PERSISTED, so the conversions will be done on the fly with each query (you don't want that).
The computed column will update itself when the row values change; otherwise the values are persisted and queryable just like in any other column. No triggers required.
If all your rows containing dates use the same date format you could just order by their string value. But since the most common (i.e english) date format does NOT start with the year, that could prove problematic.
Option A.: Sort in memory.
var records = db.YourTable.Where(o=>o.Discriminator =="date").AsEnumerable()
.Select(o=>new {Entity= o, Date=DateTime.Parse(o.YourColumn)})
.OrderBy(o.Date).Select(o=>o.Entity);
Do NOT do this if you have a lot of rows, or if you have to, at least have the decency to cache the ordered result...
Option B.: Database magic
Add an extra column to your DB, make THAT Date (nullable), and update that if the discriminator is date. You can either update it in a (DML) Trigger or from C#...
OR if the conversion is simple you could build a view out of it...
I'm having a problem with some T-SQL in a SP on SQLServer 2005 comparing dates. I'm running the stored procedure from c# with ADO.Net and passing a the native c# datetime datatype(could this be my issues as I know the ranges are slightly different). I do the following to compare 2 DateTime values in my SP.
CREATE PROCEDURE [dbo].[spGetLikelyMatchedIndividuals_v1]
#ID BIGINT = NULL,
#DOB DATETIME = NULL, ...
WHERE ISNULL(CONVERT(CHAR(8),Ind.[DateOfBirth],112),'') = ISNULL(CONVERT(CHAR(8),#DOB,112),'')
This works fine in most cases but from some reason will fail with some Datetime. This is one datetime value that fails:
1925-07-04
Does anyone have anyidea why this may fail? Also what is the best way to compare two date values without the time component?
Seems like your date compare is correct. It may be other logic that is causing this issue. Perhaps you should paste in more of your stored procedure to find the likely problem.
Better yet, don't do any logic against the table as this will prevent your index from being used.
Let your front end app handle the ensuring that the #DOB variable is in the correct format.
If you're comparing dates on SQL-Server, investigate the DateDiff function.
You can compare two dates quite easily and specify the granularity, eg. to the nearest day or hour or minute or whatever.
In your example, one of your values is a datetime, so convert the other to that type using the Convert function.
You just want to compare the date component? You could compare
FLOOR(CAST(x.[SomeDate] as float)) = FLOOR(CAST(#SomeDate as float))
A lot less string work, and should do the job. Even better; create a 1-day range and use that...
DECLARE #from datetime, #to datetime
SET #from = CAST(FLOOR(CAST(#SomeDate as float)) as datetime)
SET #to = DATEADD(day, 1, #from)
...
WHERE x.[SomeDate] >= #from AND x.[SomeDate] < #to
String operation is expensive at times. Here is an example of selecting dates ignoring the time part without any casting:
Select dateadd(dd,0, datediff(dd,0, yourdatetimeval)) as date_column