简体   繁体   中英

How to use date data type in either MS Access or SQL Server when using ODBC connection

I have a program in C# which connects to a database using a DSN (ODBC driver).

All queries I run in the program uses SQL. All works well but when using datetime data type in queries (in SELECT statement or in WHERE clause).

When DSN is a MS ACCESS database, I have to use something like this:

WHERE SomeDate = #1/1/2005#

But if the same database is in SQL Server, i should use something like this:

WHERE SomeDate = '1/1/2005' 

Is there a way to manage this in the same program without doing a routine for SQL Server and another for MS ACCESS?

I tried by getting properties of OdbcConnection object, but I could not find a way to detect if driver is MS Access or SQL Server.

You probably have used data type Datetime2 in SQL Server. That will be read as text if using the native SQL Server ODBC driver.

So either:

  1. Use the Microsoft® ODBC Driver 11 for SQL Server® - or newer, 17 is current:

Microsoft® ODBC Driver 17 for SQL Server®

  1. Change the data type of the field to DateTime

You can set your Access database to be in ANSI-92 mode. This will allow you to query date fields with single quotes.

A word of warning though if this is an existing database or there are other applications using it. This may introduce a breaking change to any existing queries in your database that are not ANSI compliant. Likewise, if there are other applications using this database their queries may also break.

Also as an alternative, please note that OdbcConnection does have a Driver property that you can probe to determine the data source. On my machine, a DSN pointing to a SQL Server database returns sqlncli11.dll , because I am using the SQL Server Native Client 11.0. You can use this property to drive the syntax of your queries in your application. You could create a data access layer that abstracts some of this away from the rest of your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM