Question

I am working on windows application. Here I need to create stored queries at runtime in MS Access 2007. (i.e on button click) for the Select, Insert, Update, delete, How to call the queries from the form based on the parameters ?

cmmd.CommandText = "CREATE TABLE tblCustomers ([CustomerID] AUTOINCREMENT PRIMARY KEY, CustomerName Text(50), [CategoryID] Long REFERENCES tblCategories (CategoryID), [IsActive] YesNo, [ModifiedBy] Long REFERENCES tblUsers (UserID), [ModifiedDate] Date)";
cmmd.ExecuteNonQuery();

//Above Create table tblCustomers executed successfully,  

cmmd.CommandText = @"CREATE PROCEDURE prAddCustmer (CustName Text(50), CatID Long, Inact No, ModBY Long, ModDate date ) AS INSERT INTO tblCustomers  (CustomerName , CategoryID, Inactive, ModifiedBy, ModifiedDate) VALUES(CustName, [CatID], [Inac], [ModBy], [ModDate]);";
cmmd.ExecuteNonQuery();
//But got error in Create Procedure prAddCustomers, Please find error in the Stored query and suggest the correct answer 
//Syntax error in PARAMETER clause.
Was it helpful?

Solution

If you want to create a new stored query in your Access database you should simply prepare a command and execute it.

For example, supposing you have a customer table and you want to retrieve the record of a single customer using a query.

To create the query

 string cmdText = @"CREATE PROCEDURE Customer_SelectOne (custID Long) as
     SELECT * FROM Customers WHERE IDCustomer = [custID]";
 OleDbCommand cmd = new OleDbCommand(cmdText, connection);
 cmd.ExecuteNonQuery();

To call the query, it is again a simple command flagged as CommandType = CommandType.StoredProcedure

 string cmdText = "Customer_SelectOne";
 OleDbCommand cmd = new OleDbCommand(cmdText, connection);
 cmd.CommandType = CommandType.StoredProcedure;
 cmd.Parameters.AddWithValue("custID", customerID);
 OleDbDataReader reader = cmd.ExecuteReader();

The example above is really simple. For more complex scenario, you need to look at the reference in the area of MS-Access Data Definition Language.

EDIT

Syntax:

CREATE PROCEDURE ProcName 
                 (optional list of parameters with type and size for Text)
                    AS
                 (Valid SQL Statement using the optional parameters list)

so this should be your 'prAddCustomers'

cmmd.CommandText = @"CREATE PROCEDURE prAddCustomers 
                     (CustName Text(50), 
                      CatID Long, 
                      IsActive BIT, 
                      ModBY Long, 
                      ModDate DATETIME )
                    as
                    INSERT INTO tblCustomers 
                      (CustomerName, CategoryID, IsActive, ModifiedBy, ModifiedDate) 
                    VALUES([CustName], [CatID], [IsActive], [ModID],[ModDate])";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top