I'm currently using Visual Web Developer 2010 (Express) and I'm trying to use the NOW() command within a SQL query to allow date selection but it doesn't work at random times and I'm lost to why it does this.
I'll give some examples, I'm from the UK my machine is set to standard time (sync with time.windows.com) and everything is fine but when I use the = NOW() it works but when it doesn't it seems the input date is mixed up, example below:
Currently my table is set as follows:
Table crew_example:
Column 1 : Date (In standard SQL time, so YYYY-MM-DD)
Column 2 : Initial
Column 3 : Surname
etc
My SQL query is as follows:
SELECT Date,
Initial,
Surname,
FROM crew_example
WHERE ( Date = { fn NOW() } )
ORDER BY Date
This function normal work and is currently working with another SQL query that users BETWEEN (DATE = { fn NOW() } + 1) AND { fn NOW() } + 6) (Which I had trouble when I set this up before but it magically fixed itself and never thought anything about it).
The date output when I hardcode doesn't work if I use today's date 27/11/2014 but works when I "americanise" it to 11/27/2014 even though the output comes in UK format 27/11/2014 00:00:00
Is there a way to unify the dates? I'm new to SQL queries so not use if I can use the NOW() command but change it to NOW() in format MM/DD/YYYY instead of what looks to be NOW() using my UK date type.
EDIT: Seems CURRENT_DATE may work....but any ideas if this is the best way?
Regards
Jamie
In T-SQL I would use something like this:
Where Date between cast(getdate() as date) and cast(dateadd(d,1,getdate()) as date)
I've never used a "pure" date column, so I'm not sure if you need to get rid of the time with the cast.
For dateadd() see: DATEADD (Transact-SQL)
For cast() see: CAST and CONVERT (Transact-SQL)
Related
i use oracle forms 11g. And i pass To_Date(sysdate,'dd-mm-yyyy') that is inserted to the data base and data type of the column is date. but it is inserted as 22-10-0015 instead of 22-10-2015 can you help me?
i use procedure to insert data s and oracle from button click.i need to insert dd-mm-yyyy format to the data base how to do this?
sysdate is already a date, so it doesn't make sense to call to_date() for it. You are implicitly converting it to a string, and then explicitly back to a date. The implicit step is using your Forms session's NLS_DATE_FORMAT, which is presumably DD-MM-YY from the symptoms, so you're really doing:
to_date(to_char(sysdate,'dd-mm-yy'),'dd-mm-yyyy')
The implicit string version would show the year as 15 if you ran that on its own; and the explicit conversion correctly sees that as 0015 rather than assuming 2015.
You should just pass sysdate directly; but if you're trying to strip out the time so it shows as midnight, you can use the trunc() function:
trunc(sysdate)
SYSDATE is already a DATE. You don't need to use TO_DATE to convert it into a DATE.
What it's happening is that you're converting SYSDATE into a string and you're using the YYYY mask which will translate any year over 2000 into the 00's (that's why 2015 is being converted to the year 15). If you use the RRRR mask you will get the expected result:
TO_DATE(SYSDATE,'dd-mm-rrrr')
However, this is not a good idea as it's unnecesary and could fail if the NLS_DATE_FORMAT model used for the implicit conversion to string doesn't match.
I have the following piece of inline SQL that I run from a C# windows service:
UPDATE table_name SET
status_cd = '2',
sdate = CAST('03/28/2011 18:03:40' AS DATETIME),
bat_id = '33acff9b-e2b4-410e-baaf-417656e3c255',
cnt = 1,
attempt_date = CAST('03/28/2011 18:03:40' AS DATETIME)
WHERE id = '1855'
When I run this against a SQL Server database from within the application, I get the following error:
System.Data.SqlClient.SqlException: The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.
But if I take the piece of SQL and run it from SQL Management Studio, it will run without issue.
Any ideas what may be causing this issue?
Ambiguous date formats are interpreted according to the language of the login. This works
set dateformat mdy
select CAST('03/28/2011 18:03:40' AS DATETIME)
This doesn't
set dateformat dmy
select CAST('03/28/2011 18:03:40' AS DATETIME)
If you use parameterised queries with the correct datatype you avoid these issues. You can also use the unambiguous "unseparated" format yyyyMMdd hh:mm:ss
But if i take the piece of sql and run it from sql management studio, it will run without issue.
If you are at liberty to, change the service account to your own login, which would inherit your language/regional perferences.
The real crux of the issue is:
I use the following to convert -> date.Value.ToString("MM/dd/yyyy HH:mm:ss")
Please start using parameterized queries so that you won't encounter these issues in the future. It is also more robust, predictable and best practice.
I think the best way to work with dates between C# and SQL is, of course, use parametrized queries, and always work with DateTime objects on C# and the ToString() formating options it provides.
You better execute set datetime <format> (here you have the set dateformat explanation on MSDN) before working with dates on SQL Server so you don't get in trouble, like for example set datetime ymd. You only need to do it once per connection because it mantains the format while open, so a good practice would be to do it just after openning the connection to the database.
Then, you can always work with 'yyyy-MM-dd HH:mm:ss:ffff' formats.
To pass the DateTime object to your parametrized query you can use DateTime.ToString('yyyy-MM-dd HH:mm:ss:ffff').
For parsing weird formatted dates on C# you can use DateTime.ParseExact() method, where you have the option to specify exactly what the input format is: DateTime.ParseExact(<some date string>, 'dd/MM-yyyy',CultureInfo.InvariantCulture). Here you have the DateTime.ParseExact() explanation on MSDN)
It's a date format issue. In Ireland the standard date format for the 28th of March would be "28-03-2011", whereas "03/28/2011" is the standard for the USA (among many others).
I know that this solution is a little different from the OP's case, but as you may have been redirected here from searching on google the title of this question, as I did, maybe you're facing the same problem I had.
Sometimes you get this error because your date time is not valid, i.e. your date (in string format) points to a day which exceeds the number of days of that month!
e.g.: CONVERT(Datetime, '2015-06-31') caused me this error, while I was converting a statement from MySql (which didn't argue! and makes the error really harder to catch) to SQL Server.
You could use next function to initialize your DateTime variable:
DATETIMEFROMPARTS ( year, month, day, hour, minute, seconds, milliseconds )
JAVA8: Use LocalDateTime.now().toString()
i faced this issue where i was using SQL it is different from MYSQL
the solution was puting in this format:
=date('m-d-y h:m:s');
rather than
=date('y-m-d h:m:s');
I'm trying to do a Datediff in VB.Net thats confusing me.
Basically I'm trying to do the following.
If DateDiff("D", Today(), rsData("Start")) > 0 Then
This is working fine when comparing the value from SQL with todays date. I however need to convert this to check the current month and if it matches then return whatever I'm trying to show below.
The SQL field format is as follows - 2012-01-03 00:00:00.0000000
Thanks!
'Is the data's month equal to today's month?
If Today.Month = CDate(rsData("Start")).Month Then
End If
I have a textbox which displays the date as 01-May-2011 but the database coumis in format of datetime ... how to enter date in date time column of database. ..
how to wite the sqlquery for this ?
You can convert that format to a DateTime like this
string dateString = "01-May-2011";
string format = "dd-MMM-yyyy";
var result = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture);
if you're using LINQ to SQL or even ADO with a parameter of type DateTime, the conversion to a format that SQL understands will be done automatically for you.
If you're building the SQL by concatenating a string manually (not recommended!) you should try to reconvert to a string in the format 'yyyyMMdddd' (corrected as per AdaTheDev's comment, notice the single quotes). Other formats may or may not be recognized by sql depending on the language settings on both your client and your SQL Server
SQL Server is pretty good about taking in datetime values. If you pass the date as a parameter you can put quotes around it ('01-May-2011') and ignore the time. The database will automatically fill in a default time so that you don't have to worry about it.
Pass field value as nvarchar to database and use following to cast it to datetime.
Declare #dt nvarchar(20)
SET #dt = '01-May-2011'
select cast(#dt as datetime)
One thing to be aware of is that dates w/o time will be interpreted as May 1 2011 12AM. IE, without a time specified, SQL Server will always set the time to midnight. So if you have just the date as a field and you want records from May 1, you can't do
WHERE datefield = '5/1/2011'
This will find records where the datefield is May 1st Midnight. You have to do
WHERE datefield >= '5/1/2011' and datefield < '5/2/2011'
This doesn't really pertain to your question, but I've seen it trip up a LOT of people. Myself included.
Just convert it to dateTime
DateTime _ConvertedDate = Convert.ToDateTime(txtDate.Text);
this converts into datetime
I am new to development and want to know the professional way to deal with dates in SQL Server. In my applications mainly we deal with the DATE datatype and no concern with time part. Also maintaining the format dd/mm/yyyy
So for example if I have the table with the following structure.
EmployeeTable
---------------
emp_id int
emp_name varchar(50)
join_date date
and if I want to query "join_date" in between start date and end date and pass the dd/mm/yyyy as stored procedure criteria and want to query.
What is the professional way to handle dates? I always convert date in varchar and then do the comparison which I guess is the unprofessional way of doing it. So please guide how to do it in procedure with example I would appreciate.
SQL handles dates just fine, so you do not need to convert the dates.
If you pass in the parameters as date types, then you will have no problem:
CREATE PROCEDURE myProc
#start date,
#end date
AS
SELECT emp_id, emp_name, join_date
FROM EmployeeTable
WHERE join_date BETWEEN start AND end;
Unless you want to format a date in your output in a specific way, there's no reason to convert the date to a varchar. You're using the date datatype, so let SQL do the comparisons for you.
If you want to compare dates in a date range, you can use this:
WHERE join_date BETWEEN '2010-01-01' AND '2010-12-31'
Keep dates as dates. Do not convert it to strings. That is unnecessary.
When you send dates in to SQL Server from your code, do it with parameters, then you don't have to worry about the right format in your strings.
SQL Server Date data types:
Date: 0001-01-01 through 9999-12-31
SmallDateTime: 1900-01-01 through
2079-06-06 (Accuracy 1 minute)
DateTime: January 1, 1753, through
December 31, 9999 (Accuracy
millisecond)
DateTime2: 0001-01-01 through
9999-12-31 (Accuracy 100 nanoseconds)
It's a minor point but worth noting that all queries presented to SQL Server are in TEXT. At some stage, based on some language and translation setting in the data access layer (OLEDB, Native, ADO) it gets turned into a textual form, so dates are always presented as "text".
The best format to use is always YYYYMMDD for SQL Server. Even YYYY-MM-DD can be wrong, for obscure dateformat settings. See this example.
set dateformat dmy -- more than common for non-US locations
select CONVERT(varchar, convert(datetime, '2010-12-31'), 112)
It fails.
Msg 242, Level 16, State 3, Line 3
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
That covers the format to use when you have to construct the date embedded in the SQL statement. When possible however, please parameterize queries for benefits like
prevention of SQL injection
letting the db connectivity layer ensure the right formats when generating the TSQL
query plan re-use on the SQL Server
point 3 = better performing queries and more efficient SQL Server