简体   繁体   中英

How to ignore MS Access “Type Conversion Error” when running SQL statement from C#?

I have an MS Access database with a table with hundreds of columns. When running my SQL INSERT INTO query, one (or more) of the fields cause a "Type Conversion Error", which is fine because it works anyways. When I run this process of SQL INSERT INTO via the MS Access GUI I simply ignore the popup message.

eg:

INSERT INTO tbl_Log (ID, PID, Customer_ID...)
SELECT tbl_Data.ID, tbl_Data.PID, tbl_Data.Customer_ID...
FROM tbl_Data

However, when I run the query via C# and send the query string via Oledb, the query fails (I suspect due to the type conversion error). How can I ignore this error and proceed with the query.. via C#?

Is there an option in the GUI to "ignore all type conversion warnings" or a way to modify my SQL string? Or do I have to go through all the hundreds of columns and make sure they are all the right type.

When executing an "action query" (INSERT, UPDATE, or DELETE) in Access we are offered a choice of how to proceed if errors are encountered. For example, given an empty table named [tbl_Log] with fields

ID - Long Integer, Primary Key
DateValue - Date/Time

and a table named [tbl_Data] with fields

ID - Long Integer, Primary Key
DateString - Text(10)

and sample data

ID  DateString
--  ----------
 1  2016-01-01
 2  (unknown)
 3  2016-03-03

if we run the query

INSERT INTO tbl_Log (ID, DateValue)
SELECT ID, DateString
FROM tbl_Data;

we see a dialog that says, in part

Microsoft Access set 1 field(s) to Null due to a type conversion failure, ...

To ignore the error(s) and run the query, click Yes.

If we click "No" then the entire INSERT is cancelled. If we click "Yes" then the valid data is inserted and the invalid value(s) are set to Null:

ID  DateValue
--  ----------
 1  2016-01-01
 2  
 3  2016-03-03

From a .NET application, System.Data.OleDb does not have the "ignore the error(s)" option but Access DAO does. So, to achieve the same effect as clicking "Yes" in the Access dialog we can do

// This code requires the following COM reference in your project:
//
//     Microsoft Office 14.0 Access Database Engine Object Library
//
// and the declaration
//
//     using Microsoft.Office.Interop.Access.Dao;
//
// at the top of the class file            

var dbe = new DBEngine();
Database db = dbe.OpenDatabase(@"C:\Users\Public\Database1.accdb");
string sql =
        "INSERT INTO tbl_Log (ID, DateValue) " +
        "SELECT ID, DateString " +
        "FROM tbl_Data";
db.Execute(sql);

Note that the .Execute method does not use the RecordsetOptionEnum.dbFailOnError option, which would be the equivalent to clicking "No" in the Access dialog and cancelling the entire operation.

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