简体   繁体   中英

Creating a query (with function) in C# for an Access database

I need to create a query within my C# application on an MS Access table. However, this query will need to call a function (converting an [Employees] numeric field to a text field called [Employee Band] - 1 to 5, 5 to 10 etc). Originally, I created the query within Access (with function in place), but could not call it from C# without adding extra add-ins to the app (something I don't really want to do).

I have no idea how to do this (with ac# function doing the conversion), so any help would be greatly appreciated.

I have added some rough code (even though I know it is not correct), but it should give you some idea as to what I am trying to do:

private void EmployeeTest()
{
    using (var con = new OleDbConnection())
    {
        //Removing any existing data
        con.ConnectionString = DBConnections.ConnStringCO;
        con.Open();
        using (var cmd = new OleDbCommand())
        {
            cmd.Connection = con;
            cmd.CommandType = System.Data.CommandType.Text;
            cmd.CommandText = @"INSERT INTO [Report data] ( [Employee band] ) IN 'C:\\Users\\Dev\\Reporting-System.mdb' SELECT repEmployeeBand([Employees]) AS ExprExmployeeBanding FROM [tblSource Dat];";
            cmd.ExecuteNonQuery();
        }
        con.Close();
    }

}
private string ExprExmployeeBanding(Variables varEmployees) as long
{
     //Do converstion
}

I don't think you need to bother doing the conversion in C#; you should be able to create a saved query in Access that will do the conversion. For a table named [Companies]:

ID  CompanyName  Employees
--  -----------  ---------
 1  GordCo               3
 2  SampleCo             7
 3  BigCo            10000

a saved query named [qryCompanyInfo]

SELECT 
    Companies.*, 
    Switch([Employees] Between 1 And 4, "1-4", [Employees] Between 5 And 9, "5-9", True, "10 or more") AS EmployeeBand
FROM Companies;

will return

ID  CompanyName  Employees  EmployeeBand
--  -----------  ---------  ------------
 1  GordCo               3  1-4         
 2  SampleCo             7  5-9         
 3  BigCo            10000  10 or more  

I just checked and that query works fine when called directly from a C# application using Microsoft.ACE.OLEDB.12.0 .

Additional information on the Switch() function can be found here .

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