SQL Server date query - asp.net

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

Related

How To Insert a Date using oracle form

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.

Issue with date when migrating databases between SQL Server 2008 and 2012 [duplicate]

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');

SQLite Database - Compare DateTime

I am working on a SQLite Database which contains a column which stores value in format yyyy-MM-dd HH:mm:ss. Now I need to create a filter to select rows with filter as this datetime column.
Query:
Select * from tbl_locations where datetime >= '2013-09-11 00:00:00' and datetime <='2013-09-13 00:00:00'
Above query is returning null set despite containing values in this slot(which I verified using select statement without filter.)
Any suggestion how can i get the required data set?
Perhaps this excerpt from the SQLite documentation will help you:
1.2 Date and Time Datatype
SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values:
TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS").
REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar.
INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC.
Applications can chose to store dates and times in any of these formats and freely convert between formats using the built-in date and time functions.
The date and time functions that you can use in your SQL to build your query are documented at http://www.sqlite.org/lang_datefunc.html
Ok, I tested this out in MySQL but hopefully it will work. I had a table that used timestamps, and changed the column to be of type text. Then I tried the following SQL query and got the same results that I normally would (besides trailing decimals)
SELECT timestamp(stock_quote_timestamp)
FROM stock.stock_quote
WHERE stock_quote_timestamp < timestamp('2013-10-07 11:05:30')##high_date
AND stock_quote_timestamp > timestamp('2013-10-03 14:09:03');##low_date;
So basically, just convert your text statements to timestamps so that they compare correctly. Oh, and you'll also need to state what else you're SELECTing, or you could do a compound select statement: SELECT *, timestamp(stock_quote_timestamp)...

How can I store the current timestamp in SQLite as ticks?

I have a SQLite database where I store the dates as ticks. I am not using the default ISO8601 format. Let's say I have a table defined as follows:
CREATE TABLE TestDate (LastModifiedTime DATETIME)
Using SQL, I wish to insert the current date and time. If I execute any of the below statements, I end up getting the date and time stored as a string and not in ticks.
INSERT INTO TestDate (LastModifiedTime) VALUES(CURRENT_TIMESTAMP)
INSERT INTO TestDate (LastModifiedTime) VALUES(DateTime('now'))
I have looked at the SQLite documenation, but I do not seem to find any option to obtain the current timestamp in ticks.
I can of course define a parameter in C# and store the value as a System.DateTime. This does result in the datetime getting stored to the database in ticks.
What I would like to do is be able to insert and update the current timestamp directly from within the SQL statement. How would I do this?
Edit:
The reason I want the data stored as ticks in the database, is that the dates are stored in the same format as stored by the ADO.Net data provider, and so that when the data is also queried using the ADO.Net provider it is correctly retrieved as a System.DataTime .Net type.
This particular oddity of SQLite caused me much anguish.
Easy way - store and retrieve as regular timestamp
create table TestDate (
LastModifiedTime datetime
);
insert into TestDate (LastModifiedTime) values (datetime('now'));
select datetime(LastModifiedTime), strftime('%s.%f', LastModifiedTime) from TestDate;
Output: 2011-05-10 21:34:46|1305063286.46.000
Painful way - store and retrieve as a UNIX timestamp
You can use strftime to retrieve the value in ticks. Additionally, to store a UNIX timestamp (roughly equivalent to ticks), you can can surround the number of seconds in single-quotes.
insert into TestDate (LastModifiedTime) values ('1305061354');
SQLite will store this internally as some other value that is not a UNIX timestamp. On retrieval, you need to explicitly tell SQLite to retrieve it as a UNIX timestamp.
select datetime(LastModifiedTime, 'unixepoch') FROM TestDate;
To store the current date and time, use strftime('%s', 'now').
insert into TestDate (LastModifiedTime) VALUES (strftime('%s', 'now'));
Full example:
create table TestDate (
LastModifiedTime datetime
);
insert into TestDate (LastModifiedTime) values (strftime('%s', 'now'));
select datetime(LastModifiedTime, 'unixepoch') from TestDate;
When executed by sqlite3, this script with print:
2011-05-10 21:02:34 (or your current time)
After further study of the SQLite documentation and other information found on date number conversions, I have come up with the following formula, which appears to produce correct results:
INSERT INTO TestDate(LastModifiedTime)
VALUES(CAST((((JulianDay('now', 'localtime') - 2440587.5)*86400.0) + 62135596800) * 10000000 AS BIGINT))
Seems like a painful way to produce something that I would expect to be available as a built-in datetime format, especially that the database supports the storing of datetime values in ticks. Hopefully, this becomes useful for others too.
Update:
The above formula is not perfect when it comes to daylight savings. See section Caveats And Bugs in SQLite docs regarding local time calculation.
The following will return the number of milliseconds since the UNIX Epoch:
SELECT (strftime('%s', 'now') - strftime('%S', 'now') + strftime('%f', 'now')) * 1000 AS ticks
It works by grabbing the number of seconds since the Unix Epoch (%s), subtracting the number of seconds in the current time (%S), adding the number of seconds with decimal places (%f), and multiplying the result by 1000 to convert from seconds to milliseconds.
The subtraction and addition are to add precision to the value without skewing the result. As stated in the SQLite Documentation, all uses of 'now' within the same step will return the same value.

SQL Express storing date in MM/DD/YYYY format

I have an ASP.NET program that is writing date to an SQLExpress Database date field in DD/MM/YYYY.
When I look at the data in SQL Express it is stored as mm/dd/yyyy.
How can I configure it to store in DD/MM/YYYY format?
This is not possible, as the date is internally stored as a number, the DD/MM/YYYY or MM/DD/YYYY format is only the display format of the data. You can, however, change the way the data are converted to a string by SQL functions...
You are seeing the a rendered, localised version of an internal date representation (numbers of days since 01 Jan 1900 basically).
Don't worry about it. You'll get date back to your client (in an internal date representation) and this can be formatted how you like there.
Store the data normally. When you retrieve the data, do something like this on the code:
dateField.ToString("dd/MM/yyyy")
And your result will be: 11/04/2011
Maybe you can select that like this:
select CONVERT(varchar(12) , getdate(), 103 )

Resources