Article Options
Recently Viewed
Premium Sponsor
Premium Sponsor

 »  Home  »  Data Programming  »  Working with MS Access Stored Procedures in VB.NET. Part 1
 »  Home  »  Data Programming  »  Microsoft Access  »  Working with MS Access Stored Procedures in VB.NET. Part 1
Working with MS Access Stored Procedures in VB.NET. Part 1
by David Wasserman | Published  02/27/2002 | Data Programming Microsoft Access | Rating:
David Wasserman

David Wasserman is a Senior Software Developer residing in Toronto, Canada. He has over 10 years industry experience in a vast array of technologies and programming languages. David has also consulted for many companies in the banking, retail and communications industries via Grand Solutions Consulting Inc, where he is Vice-President. In recent years, David's focus has been working with Microsoft technologies, including Visual Basic, VB.NET, C#, ASP, ASP .NET, SQL Server and MS Access development. David can be reached at david@grandconsult.com.

 

View all articles by David Wasserman...
Working with MS Access Stored Procedures in VB.NET. Part 1

Article source code: msaccess_sp.zip

Introduction

In the more recent releases of Microsoft Access, great effort has gone into making this product a full-featured relational database system. Stored procedures, a functionality usually associated with enterprise database systems such as SQL Server, can now be found in Access. Stored procedures in Access have been available since Access 2000 and are native to the Jet 4 Database Engine. If you're accustomed to using stored procedures in SQL Server, then you'll be right at home with how they're used in Access. However there are some limitations to keep in mind. I'll discuss those later on.

This article will be broken down into two parts. Part one will describe in detail how to create stored procedures in Access using ADO.NET and Visual Basic.NET. Part two will demonstrate how to utilize the stored procedures created in part one by assembling a data access tier that can be modelled and used in your own applications. The code in this article has been tested using Access 2002, although it should also work with Access 2000.

How do stored procedures work in Access?

Unlike other objects in Access, stored procedures have no interface and cannot be created or run through the Access User Interface. The way to get them into your database is to simply code them. I'll show how that's done in ADO.NET.

When a stored procedure is added to an Access Database, the Jet Engine reworks the stored procedure syntax into a query object. To an Access developer this may sound like unnecessary work to code a query. However, it does have its advantages. Consider an application that has to break out into different versions when maintaining both an Access Database and a SQL Server Database. Using stored procedures will make it easier to write the code for the database tier of the application as the program will change very little between the different versions.

Creating Stored Procedures

To demonstrate, I'll first show how to create the SQL statements to create stored procedures. At the end of the article I'll show the entire code needed to run these statements against the database. Using the Northwind database that comes with Access, four stored procedures will be created. Focusing on the Products table for all of them, let's start off with the easiest one; select all data of each row in the table. To create the stored procedure, execute the following SQL statement against the database:

"CREATE PROC procProductsList AS SELECT * FROM Products;"

The statement: "CREATE PROC procCustomerList" is the part that actually creates the stored procedure. The part following "AS" can be any valid SQL Statement.

Often in a stored procedure you'll want to pass a value to be used in the query. Consider that you may want to delete a record based on a particular ProductID. The following stored procedure shows how to do just that:

"CREATE PROC procProductsDeleteItem(inProductsID LONG)" & _
"AS DELETE FROM Products WHERE ProductsID = inProductsID;"

On the first line, notice the parenthesis right after the CREATE PROC declaration. There is a parameter defined as a Long value. This is where you add the variable to delete the record in question.

The next two statements show how to create an add and an update stored procedure for the Products table respectively. Note that not all fields are included for the sake of brevity:

"CREATE PROC procProductsAddItem(inProductName VARCHAR(40), " & _
"inSupplierID LONG, inCategoryID LONG) " & _
"AS INSERT INTO Products (ProductName, SupplierID, CategoryID) " & _
"Values (inProductName, inSupplierID, inCategoryID);"
"CREATE PROC procProductsUpdateItem(inProductID LONG, " & _
"                                   inProductName VARCHAR(40)) " & _
"AS UPDATE Products SET ProductName = inProductName " & _
"    WHERE ProductID = inProductID;"

Notice that a comma separates each parameter when more than one is specified.

Limitations

There are some limitations you may encounter here, especially if you're used to the power of SQL Server.

  • Output parameters cannot be used.
  • Don't use the @ character. The @ character is often used in Transact SQL (SQL Server), where it represents a local variable. Access doesn't always convert this character and will sometimes leave it out. This can cause esoteric bugs which can lead to premature hair loss.
  • Temporary tables are not available in Access.
  • I suspect many of the options available in Transact SQL are not available in Access as it's not Transact SQL compatible.

Conclusion

Hopefully, this article has provided some guidance in a nearly undocumented area of Access and Jet not yet explored by most. For more information on how the ADO.NET code works in the CreateStoredProc subroutine, see Getting Started with ADO.NET by Gurneet Singh. The following is a complete listing of all code presented in this article:

Imports System
Imports System.Data
Imports System.Data.OleDb

Module CreateSP

    Sub Main()

        ProductsProcs()

    End Sub

    ' Products Stored Procs to be added to the db.
    Sub ProductsProcs()
        Dim sSQL As String

        ' procProductsList - Retrieves entire table
        sSQL = "CREATE PROC procProductsList AS SELECT * FROM Products;"
        CreateStoredProc(sSQL)

        ' procProductsDeleteItem - Returns the details (one record) from the 
        ' JobTitle table
        sSQL = "CREATE PROC procProductsDeleteItem(@ProductID LONG) AS " _
            & "DELETE FROM Products WHERE ProductID = @ProductID;"
        CreateStoredProc(sSQL)

        ' procProductsAddItem - Add one record to the JobTitle table
        sSQL = "CREATE PROC procProductsAddItem(inProductName VARCHAR(40), " _
            & "inSupplierID LONG, inCategoryID LONG) AS INSERT INTO " _
            & "Products (ProductName, SupplierID, CategoryID) Values " _
            & "(inProductName, inSupplierID,   CategoryID);"
        CreateStoredProc(sSQL)

        ' procProductsUpdateItem - Update one record on the JobTitle table
        sSQL = "CREATE PROC procProductsUpdateItem(inProductID LONG, " _
            & "inProductName VARCHAR(40)) AS UPDATE Products SET " _
            & "ProductName = inProductName WHERE ProductID = inProductID;"
        CreateStoredProc(sSQL)


    End Sub

    ' Execute the creation of Stored Procedures
    Sub CreateStoredProc(ByVal sSQL As String)
        Dim con As OleDbConnection
        Dim cmd As OleDbCommand = New OleDbCommand()
        Dim da As OleDbDataAdapter

        ' Change Data Source to the location of Northwind.mdb on your local 
        ' system.
        Dim sConStr As String = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data " _
            & "Source=C:\Program Files\Microsoft " _
            & "Office\Office10\Samples\Northwind.mdb"

        con = New OleDbConnection(sConStr)

        cmd.Connection = con
        cmd.CommandText = sSQL

        con.Open()
        cmd.ExecuteNonQuery()
        con.Close()

    End Sub


End Module
Generated using PrettyCode.Encoder

Related devCity.NET articles:

How would you rate the quality of this article?
1 2 3 4 5
Poor Excellent
Tell us why you rated this way (optional):

Article Rating
The average rating is: No-one else has rated this article yet.

Article rating:3.38857142857144 out of 5
 175 people have rated this page
Article Score147587
Comments    Submit Comment

Comment #1  (Posted by Ivan Cholev on 03/10/2002)

David,

With this method, you have just shown a different way of creating a parameterized Jet query from code. I don’t see any difference if it is created through Access interface or code- the result is same. Though, in Access you can create these queries using user-friendly graphical query builder. I doubt, if it’s stored procedure at all because missing output parameters and multiple sql statements makes it what this is- a stored Jet parameterized query not just stored procedure in way it’s known in SQL Server database.

Using stored parameterized queries direct in Access database remains preferable method of executing sql queries procedures because they are faster than dynamically built, stored in database and could represent that functionality you have talked about. ‘make it easier to write the code for the database tier of the application as the program will change very little between the different versions’

However missing ability of multiple sql statements and output parameters makes simultaneously using on different databases with one code problematic. We have to code keeping in mind Jet limitations of stored queries which obviously doesn’t make our code as universal and as flexible as we would want to be.

Regards,

Ivan Cholev
www.brainbench.com/transcript.jsp?pid=156693

 
Comment #2  (Posted by Arpan De on 04/09/2002)

The stored procedures which you have shown in this article include simple SQL statements. What do I do if I want to do something like this (this is a stored procedure in SQL Server)?

CREATE PROCEDURE spName
@name varchar(50),
@email varchar(50),
@userid varchar(50),
@password varchar(50),
AS
DECLARE
@return int

IF EXISTS(SELECT UserID FROM tblName WHERE UserID=@userid)
BEGIN
SET @return=1
PRINT 'UserID Already Exists !!! Please Use A Different UserID !!!'
END
ELSE IF EXISTS(SELECT Email FROM tblName WHERE Email=@email)
BEGIN
SET @return=2
PRINT 'E-mail Address Already Exists !!! Please Use A Different E-mail Address !!!'
END
ELSE
BEGIN
INSERT INTO tblName VALUES
(@name,@email,@userid,@password)
SET @return=0
END
RETURN @return

Is it possible to create such a stored procedure in MS-Access ie one which returns an int?

Thanks,

Regards,

Arpan
 
Comment #3  (Posted by David Wasserman on 04/11/2002)

In response to Arpan De;

Unfortunately MS Access does not support the dialect of Transact-SQL that SQL Server does. Remember that an Access Stored procedure directly translates into an Access Query. That’s how it’s stored on the database. Thus, we can conclude that anything you can do in an Access Query, you can do in an Access stored procedure.
 
Comment #4  (Posted by Harry on 06/17/2002)

I, am very new to PC based software. I tried to create a procedure following your tutorial. But could not create one. Is there something missing at my end.
I, have Ms-Access 2000 loaded on my machine .... do I need something more...?

 
Comment #5  (Posted by pinoy developer on 07/18/2002)

thank you for this article... just what i wanted
 
Comment #6  (Posted by Mohammed Al-Shibli on 07/22/2002)

Hi

Its new to most of us Stored Proc in Acess.But the Q is Why ? .The differencce in speed in unnoticable and most of the features is not avaliable. Any way , the article is really easy to undestand and great idea on this unfocussed part.

THANX, and Smile :)
 
Comment #7  (Posted by ahmad Gorabi on 07/26/2002)

Enjoyed reading your article on... http://www.msdnaa.net/interchange/preview.asp?PeerID=1385

There you describe how to use .NET in association with MS Access, and
you are using: "OleDbCommand object"

http://msdn.microsoft.com/library/default.asp?url=/library/en-
us/dnoffsol02/html/ByAllReports.asp
also uses the same object.

my Q:
can one 'run/execute' a procedure (I want to run a MS Macro or Sub), on
a remote PC (creates PDF out of an MS Access report; pc has Adobe
License), using this object?

My application tool sets: VB6, MS Access2000
....and hopefully your insite....

Apprecaite any pointers.
Thank You.




 
Comment #8  (Posted by Dwayne Burbridge on 10/09/2002)

Is there a way to run a stored procedure on a Sybase database using access as the front-end?
 
Comment #9  (Posted by Gert on 10/21/2002)

Q1:
********************
How do I dectect if the stored procedure was created before or not?

Something like this in MS SQL:
"
if exists (select * from sysobjects where id = object_id(N'[dbo].[sp_SheriffDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_SheriffDetail]
GO
"

I want to detect if the sp was created before or not, and create it when needed.

Q2:
********************
How do i drop the sp in access?

thanks, gert
 
Comment #10  (Posted by Susana on 10/24/2002)

Hello i've search in everywhere and i can´t make it still.
I need to know how can i catch a exeption throwed by the store procedure
such as "attempt to insert a duplicated key..." i´m executing a storeprocedure in SyBase from
vb.net but when the storeprocedure have an error, in .net even get into the catch... what i´m doing is this:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
cmd = New OleDbCommand(" sp_Alta_Cliente ", cn)
cmd.CommandText = "sp_Alta_Cliente"
cmd.Connection = cn
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add(New OleDbParameter("@codigo", OleDbType.SmallInt))
cmd.Parameters("@codigo").Value = 7
cmd.Parameters.Add(New OleDbParameter("@nombre", OleDbType.VarChar, 20))
cmd.Parameters("@nombre").Value = "Morpho"
cmd.Connection.Open()
Try
Dim myReader As OleDbDataReader = cmd.ExecuteReader()
myReader.Close()
cmd.Connection.Close()
MsgBox("Todo bien")

Catch exc As OleDbException
MsgBox(exc.Message.ToString )
cmd.Connection.Close()
End Try
End Sub

The first time it´s work good but the second time it should trow an exeption
because the duplicated key, but it doesn´t throw any exeption.

Can you help me please????
 
Comment #11  (Posted by baby on 12/26/2002)

How can I do if I Need declare temp par in SP:
such as:
sSQL = "CREATE PROC GCcopy(id Long,code varchar(30) " & _
"AS declare ntdid Long ;" & _
"Insert no_goods3 ([code0],[factory], [principal], [memory], [address], [phone], [fax], [email], [homepage], [postalcode], [memory1]) SELECT '*',[factorycode],[principal],[memory], [factoryaddress], [factoryphone], [factoryfax],[email], [homepage],[postalcode],'' FROM [dbo].[no_factory] where [factorycode]=code ;" & _
"select ntdid=max(pkserial) from no_goods3 ;" & _
"Update no_goods3 set code0=(select code0 from no_goods3 where pkserial=id) where pkserial=ntdid ;" & _
"delete no_goods3 where pkserial=id; "
CreateStoredProc(sSQL)

MsgBox("ok")
But I Get I ERROR!
How to do It
THX!!!
 
Comment #12  (Posted by progig on 12/31/2002)

I try to add a stored procedure to an Access db (connected via ODBC DSNless, using JAVA code).

If I don't use parameters it works just fine:

"CREATE PROC spNo1 AS SELECT * FROM TABLE1"

But when I try to add parameter(s):

"CREATE PROC spNo1(param1 VARCHAR(5)) AS SELECT * FROM TABLE1 WHERE FIELD1 = param1"

I get this error:

[Microsoft][ODBC Microsoft Access Driver]Syntax error or access violation

Any idea what causes this error?

Thanx in advance


 
Comment #13  (Posted by Plucky on 02/12/2003)

Just type in your stored query by hand...go to design mode..and SQL view, and then just type in something like:

SELECT Count(CartID) AS ItemCount
FROM ShoppingCart
WHERE CartID=@strCartID;


@strCartID is the parameter you will have to populate from asp.net.
 
Comment #14  (Posted by Russ on 02/16/2003)

I realize that this article is a little old, but from all the comments so far I gather that the Access Stored Procedures must be one simple sql. My question is: using Access 2000 and ADO.NET is it possible to somehow see what the created stored procedure is. Using Access I can not determine that the stored procedures even exist (does not appear in any of the objects). From my visual studio.net server view - I can see they exist but I can't seem to view what they are. Has someone discovered a way?
thanks
 
Comment #15  (Posted by james on 03/11/2003)

Very useful. I had been producing xml output for a web application with Access and ADO.Net, using SQL calls against an Access Db. Since I cache the xml data on the client at the beginning of the session--to avoid round trip calls to the db--it was taking a while for the page to load initially. Switching over to a parameterized stored procedure has definitely boosted performance.

Before this, I hadn't found much good information on stored procedures, .Net and MS Access. Thanks!
 
Comment #16  (Posted by pat lynch on 04/08/2003)

Thank you for sharing this information.

I'm working with an existing application that is using stored procedures and SQL Server. I have to update it and I only have Microsoft Access available.

The only problem that I ran into was that my Northwind.mdb is called FPNWIND.mdb and is not in the directory which is indicated in the articles. I changed the connectionString to reflect this difference but when I ran AccessSPPart2 I still got an error msg indicating that Northwind.mdb couldn't be found....

I modified my ProgramFiles directory to include a Samples subdirectory and changed the db name from FPNWIND.mdb to NORTHWIND.mdb and copied it to the samples subdirectory and everything worked fine...
It's almost as if NORTHWIND.mdb is 'hardcoded' in somewhere but I couldn't find where...It is a puzzle and I will have to work it a bit...

Once again, thanks for the excellent info. I can now proceed with my task at hand...

Happy stored proceduring,
Pat


 
Comment #17  (Posted by pat lynch on 04/09/2003)

I was able to successfully run Parts 1 and 2.
I also was able, using Part 1, to create my own stored procedure.

I'm presuming that AccessSPPart2.exe was built from frmMain.vb and DBTier.vb, but I can't figure out how...I'd appreciate any help, since I now want to build a form and execute my stored procedure...

I also noted the files ProductListing.vb, ProductDeleteItem.vb, ProductAddItem.vb and ProductUpdateItem.vb are also used.

Again, I'd appreciate any help.

Thanks,
Pat

I can't figure how all of this is 'tied together'...


 
Comment #18  (Posted by pat lynch on 04/09/2003)

Good evening,
I can now create stored procedures and access them...

My question is: how do you delete or change an existing stored procedure.

The case in point is: I made a mistake when I wrote the query (uh, stored procedure, excuse me) but I don't know how to correct it...If I run the Step 1 procedure with the correted stored procedure, it fails....

There must be a way to do this...I'd appreciate any help...

Thanks,
Pat
 
Comment #19  (Posted by David Wasserman on 04/10/2003)

While you can't create a stored procedure from the Access designer screens, you can delete them. When a stored procedure is created, it is stored in access as a Query. From the Query designer, you'll see your stored procedure, and can delete it there.

Hope this makes sense.
 
Comment #20  (Posted by jason on 04/25/2003)

Below Is code to use a stored proc, that is written in the Access 2002 IDE, and called like an SQLServer2000 Stored proc, but im using The OleDB Adapter instead. Works Great..
'=====================================================================================================================
Dim connectionstring As String
Dim MyConnection As OleDbConnection
connectionstring = ConfigurationSettings.AppSettings("connectionstring")
Dim jiConn = New OleDbConnection(connectionstring)

Dim loginCMD As OleDbCommand = New OleDbCommand("login_user", jiConn)
loginCMD.CommandType = CommandType.StoredProcedure

Dim myParm As OleDbParameter = loginCMD.Parameters.Add("@Username", OleDbType.VarChar, 15)
myParm.Value = username.Text

Dim myParm1 As OleDbParameter = loginCMD.Parameters.Add("@Password", OleDbType.VarChar, 15)
myParm1.Value = password.Text

jiConn.Open()

Dim myReader As OleDbDataReader = loginCMD.ExecuteReader()
'=====================================================================================================================
 
Comment #21  (Posted by LJB on 05/05/2003)

Is "Query Designer" something newer than Access 2000? I am not able to find any trace of my stored procedure in Access 2000. I know its in there because it works when I call it from ASP. I can DROP it and CREATE new procedures. With each new procedure the db size grows slightly and I can verify them by runing them but where are they?
 
Comment #22  (Posted by Hobby on 06/02/2003)

to :progig
I think you should write the string like this:
"CREATE PROC spNo1(@param1 VARCHAR(5)) AS SELECT * FROM TABLE1 WHERE FIELD1 = @param1"

Good Luck
 
Comment #23  (Posted by Mubi on 08/29/2003)

Can we use DECLARE and IF statement in an access stored procedure
 
Comment #24  (Posted by zlzheng on 09/28/2003)

In response to Russ;

You can use "OpenShema(adSchemaProcedures)" method in ADO,which return all stored procedures as a recordset. In this recordset each record rrepresent a stored procedure, you can get procedure name in field "PROCEDURE_NAME" and prodecure definition in field "PROCEDURE_DEFINITION".
Of course you can also get stored procedures with ProceduresPtr in ADOX.
Hope this helpful.
 
Comment #25  (Posted by greg on 10/30/2003)

um yeah
sounds time savingly orgasmic
how does one run this code to create a stored proc in access
thank you
 
Comment #26  (Posted by Jason on 01/19/2004)

I have a forum table. When I want to display a list of messages from it, I typically give it a particular forumid (category of thread). So my stored procedure includes this. What if I want the ability to execute the stored procedure and have the list of messages include posts from all forums categories? Can there be a default value (if I don't supply it) or a wildcard I can give for the forumID parameter?

here's my stored procedure code if it helps...
SELECT *
FROM forum
WHERE forumID = @ForumID;

In my ASP page I use the following recordset command...
myRS.Open "Exec sp_getMessageList " & ForumID, myForumConn

 
Comment #27  (Posted by Nikolai Serdiuk on 03/26/2004)

I creates some stored procedures, for SELECT, DELETE, UPDATE. The stored procedures for SELECT and DELETE works fine. But when I try to execute the UPDATE stored procedure I get following error:

System.Data.OleDbException: Cannot update 'UserName'; field not updateable.

I checked the stored procedure's UPDATE query, it worked when started as query. Also the stored procedure parameters are passed properly. Here is the stored procedure code:

CREATE PROCEDURE procUpdateUser(nUserID LONG, UserName VARCHAR(30), Name VARCHAR(50),
Surname VARCHAR(50), Representative VARCHAR(10), CRMServer VARCHAR(40),
[Password] VARCHAR(16), IsAdministrator BIT)
AS
UPDATE
[Users]
SET
[UserName] = UserName,
[Password] = [Password],
[Surname] = Surname,
[Name] = Name,
[RepresentativeNumber] = Representative,
[CRMServer] = CRMServer,
[IsAdministrator] = IsAdministrator
WHERE
[UserID] = nUserID

It seams that is some security problem. Can anyone help me?

Thanks in advance,
Nikolai


 
Comment #28  (Posted by Richard on 06/17/2004)

Please someone put an example with 2 or more rows of code (a full select counts 1 row!) working. The code above with many DIMs does not work!
create proc myproc
as
{first row that does something (A working dim s as string would be apreciated)}
{second row that does something}
 
Comment #29  (Posted by John Winstanley on 06/23/2004)

I couldn't see the queries I had created when I connected to an Access 2000 database
I tried changing this option
tools->options->view->hidden
But it did not help.
This seems to be a bug in Access 2000

as I could succefully see the queries when I used Access 97

Reading other comments someone else experienced this also.

John


 
Comment #30  (Posted by Peka on 06/28/2004)

How can I call storage procedure (on Oracle) from MS ACCESS?
I use pass-trough query, ODBC is ok, and it's work when I use SELECT,INSERT...
but How GET OUT parameters from procedure in MS Acccess.

Please Help!

 
Comment #31  (Posted by al on 06/29/2004)

I've been playing around with what was given in part1 and part2 and i don't understand why it isn't working for me. I ran the code given in part1 and for some reason i cannot create a sp. It keeps throwing an exception around here.
con.Open()
cmd.ExecuteNonQuery()
con.Close()
I've even created my own database instead of using the northwind and i even wrote my own easy sp and it still giving me problems. I looked at ms access 2000 and i cannot find any sp so i am assuming that vb code did not create it. I even tried to add a module CreateSP module in the project and still nothing happening, can anyone please help me out here? btw, the path is correct and i even double checked it so i don't think has anything to do with the connectionString.
 
Comment #32  (Posted by Todd Harvey on 08/19/2004)

here's three stored procedures, each with "many" parameters

// from http://www.devcity.net/net/article.aspx?alias=msaccess_sp
private void Create_StoredProcedure()
{
string strSQL = "CREATE PROC UpdateDetails3( inID LONG , "
+ " inCompany VARCHAR(255), "
+ " inNames VARCHAR(255), "
+ " inLanguages VARCHAR(255), "
+ " inAddress VARCHAR(255), "
+ " inPhone VARCHAR(255), "
+ " inMisc TEXT(2500), "
+ " inContact VARCHAR(255), "
+ " inWeb VARCHAR(255) ,"
+ " inAgent BIT, "
+ " inPriority LONG, "
+ " inContacted DATETIME "
+ " ) "
+ " AS UPDATE tblCompany "
+ " SET tblCompany.[Company] = inCompany ,"
+ " tblCompany.[Names] = inNames ,"
+ " tblCompany.[Languages] = inLanguages, "
+ " tblCompany.[Address] = inAddress, "
+ " tblCompany.[Phone] = inPhone, "
+ " tblCompany.[Misc] = inMisc, "
+ " tblCompany.[Contact] = inContact, "
+ " tblCompany.[Web] = inWeb ,"
+ " tblCompany.[Agent] = inAgent, "
+ " tblCompany.[Priority] = inPriority, "
+ " tblCompany.[Contacted] = inContacted "
+ " WHERE ID=inID;";

/* the below worked
string strSQL = "CREATE PROC UpdateDetails( inID LONG , "
+ " inCompany VARCHAR(255), "
+ " inNames VARCHAR(255), "
+ " inLanguages VARCHAR(255), "
+ " inAddress VARCHAR(255), "
+ " inPhone VARCHAR(255), "
//+ " inMisc TEXT(250), "
+ " inContact VARCHAR(255), "
+ " inWeb VARCHAR(255) "
//+ " inAgent YESNO, "
//+ " inPriority INTEGER, "
//+ " inContacted DATETIME "
+ " ) "
+ " AS UPDATE tblCompany "
+ " SET tblCompany.[Company] = inCompany ,"
+ " tblCompany.[Names] = inNames ,"
+ " tblCompany.[Languages] = inLanguages, "
+ " tblCompany.[Address] = inAddress, "
+ " tblCompany.[Phone] = inPhone, "
//+ " tblCompany.[Misc] = inMisc, "
+ " tblCompany.[Contact] = inContact, "
+ " tblCompany.[Web] = inWeb "
//+ " tblCompany.[Agent] = inAgent, "
//+ " tblCompany.[inPriority] = inPriority, "
//+ " tblCompany.[inContacted] = inContacted ,"
+ " WHERE ID=inID;";

strSQL = "CREATE PROC procTest2(inID LONG, "
+ "inCompany VARCHAR(40) , "
+ " inNames VARCHAR(40) "
+ " ) AS UPDATE tblCompany SET "
+ " tblCompany.[Company]=inCompany , tblCompany.[Names]=inNames WHERE ID = inID;";
*/
System.Data.OleDb.OleDbCommand ole_command = new OleDbCommand(strSQL,Globals.aConnection);
// how to refresh the grid?
try
{
ole_command.ExecuteNonQuery(); // add a new record
}
catch(System.Data.OleDb.OleDbException exO)
{
Console.WriteLine(strSQL);
Console.WriteLine("{0}",exO.ToString());
//System.Windows.Forms.MessageBox.Show(" Error in Add Line: " + exO.Message);
}
catch( Exception ex)
{
Console.WriteLine("Error: {0}", ex);
}




}

 
Comment #33  (Posted by Todd Harvey on 08/19/2004)

to delete a query:
DROP table UpdateDetails;

this works for queries too, try it.
 
Comment #34  (Posted by Katrina Deane on 10/25/2004)

I tried using CREATE PROC, but got the following error message: "Syntax error in CREATE TABLE statement." Any ideas as to why this doesn't work . I'm using MS Acess 2000 (9.0.3821 SR-1)
 
Comment #35  (Posted by Roger on 11/06/2004)

progig asked:

> But when I try to add parameter(s):

> "CREATE PROC spNo1(param1 VARCHAR(5)) AS SELECT * FROM TABLE1 WHERE FIELD1 = param1"

> I get this error:

> [Microsoft][ODBC Microsoft Access Driver]Syntax error or access violation

I had the same problem and couldn't find the answer anywhere on the Web, but finally guessed at it. This *may* be specific to an earlier version of the Jet engine, but the problem is the "(5)" in the "VARCHAR(5)" -- leave that size off, and it works:

"CREATE PROC spNo1(param1 VARCHAR) AS SELECT * FROM TABLE1 WHERE FIELD1 = param1"

 
Comment #36  (Posted by Steve on 01/13/2005)
Rating
You can view the stored procedures by using Tools->Analyze->Documenter the select Queries Tab, select your query and click OK
 
Comment #37  (Posted by an unknown user on 01/22/2005)
Rating
it is good for beginners
 
Comment #38  (Posted by Cyberitis on 01/28/2005)
Rating
If you understand why one would want to write a stored procedure in the first place you wouldn't be writing it in access. Full stop.
 
Comment #39  (Posted by Chockkalingam on 03/14/2005)
Rating
Hi,

I am a vb6 coder, I am totally new to this area, the article is clear & understandable, i have some clarifications.

1. where i have to add the Imports System,Imports System.Data,Imports System.Data.OledbClient whether in the Module or in the Form.

2. I am not able to get the (CreateStoredProc) only CreateSP is coming, what are all the Refrences & Components should be added for this project.

Thankyou,
Chock.
 
Comment #40  (Posted by an unknown user on 03/15/2005)
Rating
i m beginer ,i think it is intersting material to read
 
Comment #41  (Posted by an unknown user on 03/15/2005)
Rating
Great Article!!!!
 
Comment #42  (Posted by Chaitanya Kiran J on 03/24/2005)
Rating
Hi,
I am not an experienced programmer. I tried to create a simple SP. And it worked perfectly fine when executed for the first time. And when i executed the same the second time, it is giving an exception that Procedure already exists. And i serched the entire database for the procedure. but i could n't find the procedure.
Please help me how in finding the procedure. and how can i re-use the same in another application? Any kind of help will be appreciated...................... Thanks...

 
Comment #43  (Posted by an unknown user on 03/30/2005)
Rating
It's Ok
 
Comment #44  (Posted by an unknown user on 04/14/2005)
Rating
excellent

 
Comment #45  (Posted by venu on 04/26/2005)
Rating
i want a stored procedure to check the user id and password from vb.net front end application.
 
Comment #46  (Posted by an unknown user on 05/04/2005)
Rating
This is a very, very good example. Just what I was kind of looking for, thanks Mr Wasserman
 
Comment #47  (Posted by an unknown user on 05/09/2005)
Rating
first on stored procedures in Access
 
Comment #48  (Posted by an unknown user on 05/10/2005)
Rating
someone help Nicoli pick something else for [Password] = [Password]
 
Comment #49  (Posted by an unknown user on 05/13/2005)
Rating
good page helped a lot
 
Comment #50  (Posted by an unknown user on 05/26/2005)
Rating
hi this is excellent one,but i need code in C#.and my query is how to create stored procedure in MS-Acess itself..Is it possible to create in MS-Acess.and also how to send OleDbparameters to stored procedure..??

 
Comment #51  (Posted by an unknown user on 06/06/2005)
Rating
excelent explaination
 
Comment #52  (Posted by Amrita on 06/13/2005)
Rating
hi
is there a way we can update the created stored proc??
thnx
Amrita
 
Comment #53  (Posted by an unknown user on 06/16/2005)
Rating
i understood
 
Comment #54  (Posted by an unknown user on 07/09/2005)
Rating
Concise and to the point. Exactly what I needed to get started. Thanks!!!
.
 
Comment #55  (Posted by francisco on 07/30/2005)

This was exactly what I needed. Fantastic work!
Thank you very much!
 
Comment #56  (Posted by an unknown user on 08/19/2005)
Rating
How to set the table name like "Table-Name"
 
Comment #57  (Posted by an unknown user on 08/19/2005)
Rating
How to set the table name like "Table-Name"
 
Comment #58  (Posted by Richard on 09/12/2005)
Rating
A very nice article and also some very good comments.

I would use stored procedures for the data adapter’s Update method, if I could get them into the database.

I suspect I’m up against a permissions problem (Windows XP, Access 2003) but haven’t yet got it worked out. Any help would be appreciated…

 
Comment #59  (Posted by STAMBAY; programmer Dominic Guiritan on 09/16/2005)
Rating

hi there!!! if you like more details about stored procedure i can send a lot of stored procedure using MS JET only not in ORACLE and MySQL; just email me!!! completely i can help you with most of your problems, thanks "SHARING is the key in IT FUTURE's TECHNOLOGY" for filipino programmer just call me; 4721856 or 8535526 bye bye see youu
 
Comment #60  (Posted by Ken on 09/16/2005)
Rating
To get a list of Queries stored in an Access DB use the following Query:
Select Name FROM mSysObjects Where Type=5

Ken -CSMicro Systems
 
Comment #61  (Posted by Richard on 09/18/2005)
Rating
I got my prob figured out (it was not permissions). Nice code snippet Ken!
So long, and thanks for all the fish.
 
Comment #62  (Posted by an unknown user on 11/02/2005)
Rating
why and when stored procudure used
 
Comment #63  (Posted by an unknown user on 11/07/2005)
Rating
It would have been great if you have included the informationa as to why this method of data updates or changes is better when compared to manually creating the stored procedures in access one time and using them multiple times.
 
Comment #64  (Posted by an unknown user on 11/20/2005)
Rating
Best article on the subject!!!
 
Comment #65  (Posted by Seong-Rok Hong on 11/27/2005)
Rating
THANKS~!Your Article seems to be good help to me~^^
 
Comment #66  (Posted by an unknown user on 01/10/2006)
Rating
way you present it and description
 
Comment #67  (Posted by an unknown user on 03/01/2006)
Rating
thanks for doing all the hard work for me.
 
Comment #68  (Posted by an unknown user on 03/17/2006)
Rating
I see with good like this idea. ( Jonhy - Brazil )
 
Comment #69  (Posted by an unknown user on 04/19/2006)
Rating
As a seasoned sql server user I needed to use access - first time for a while! I usually use stored procedures but couldn't work out how to do them in access. Unlike Access's help, this article makes it clear that I can only create and use them from code rather than the access interface. Useful to know.
 
Comment #70  (Posted by an unknown user on 04/22/2006)
Rating
THis is the first I've read on stored procedures in Access. Most others only talk about it in context of SQL-Server. Thanks!
 
Comment #71  (Posted by an unknown user on 05/03/2006)
Rating
thnx David, u realy made my day..
 
Comment #72  (Posted by an unknown user on 05/03/2006)
Rating
thnx David, u realy made my day..
 
Comment #73  (Posted by an unknown user on 05/10/2006)
Rating
Very good. Solved my issues. Thanks.
 
Comment #74  (Posted by an unknown user on 05/10/2006)
Rating
Very good. Solved my issues. Thanks.
 
Comment #75  (Posted by an unknown user on 06/02/2006)
Rating
This is excellent
 
Comment #76  (Posted by an unknown user on 07/03/2006)
Rating
Just i will tell 2marow because i will see it today wheather that is execute the stored procedure properly
 
Comment #77  (Posted by an unknown user on 09/05/2006)
Rating
the information on page is good.
its realy help me.
thanks

reards
Dharmendra
 
Comment #78  (Posted by an unknown user on 09/09/2006)
Rating
Great Job Mate
Vicky Biswas
 
Comment #79  (Posted by an unknown user on 10/03/2006)
Rating
Bco'Z search must be to the point
I asked for declaration of parameter in a vb.net for the execution of an sql query in vb.net application
 
Comment #80  (Posted by an unknown user on 11/24/2006)
Rating
Create procedure in code. It's excellent.
 
Comment #81  (Posted by an unknown user on 01/16/2007)
Rating
i have create a procedure in ms access,
but now I can not drop it.

help me!
 
Comment #82  (Posted by an unknown user on 02/26/2007)
Rating
Very helpfull. Thanks
 
Comment #83  (Posted by Bishar on 03/15/2007)
Rating
I culdnt access my Database an error of "Could not Find Installable ISAM is shown always"How can i solve this.I am using M.Access 2000.All My codings are right.Pls
Do rply Urgent.
 
Comment #84  (Posted by Bishar on 03/15/2007)
Rating

Thi is my code i have an error"Could not find installble ISAM"

Dim con As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;;DataSource=D:\Filelist.mdb")
Dim cmd As OleDbCommand = New OleDbCommand
Dim ada As OleDbDataAdapter = New OleDbDataAdapter
Dim dt As New DataTable

Try
cmd.Connection = con
cmd.CommandText = "select * from Filelist"
ada.SelectCommand = cmd
ada.Fill(dt)
DataGrid1.DataSource = dt
Catch ex As Exception
MessageBox.Show(ex.Message)

 
Comment #85  (Posted by an unknown user on 04/09/2007)
Rating
An excellent overview of a mostly undocumented topic.
 
Comment #86  (Posted by an unknown user on 04/11/2007)
Rating
thanks for the help!
 
Comment #87  (Posted by an unknown user on 04/20/2007)
Rating
that was really useful, helped me to understand stored procs in access
 
Comment #88  (Posted by an unknown user on 05/06/2007)
Rating
This guide is really helpful with one little exception: the OLEDB does not support the named parameters in stored procedures. It took me half a day to figure it out. So instead of the above the Update procedure looks like this: UPDATE Products SET ProductName=? where ProductID=?. In the VB.NET code be careful adding the parameters in the right order (ProductName the ProductID). The parameter.name= ... lines are useless.
 
Comment #89  (Posted by an unknown user on 07/11/2007)
Rating
Great! Helped a lot!
 
Comment #90  (Posted by an unknown user on 07/12/2007)
Rating
plz show the way to create the stored procedure in access
 
Comment #91  (Posted by sudhir on 08/17/2007)
Rating
how to pass table name as argument in Ms_access stored
procedure . is it possible or not .
 
Comment #92  (Posted by an unknown user on 09/20/2007)
Rating
I GET WHAT I AM LOOKING FOR
 
Comment #93  (Posted by an unknown user on 09/25/2007)
Rating
Really helpful for me.
Thanks for the article. I need to run this logic and see the results.
Thanks,
Prabhat Joshi
 
Comment #94  (Posted by an unknown user on 12/13/2007)
Rating
Hi David, It is not widely known but temp tables have been available to MS Access programmers for years.
TJ Hock
tj_hock@yahoo.com
 
Comment #95  (Posted by an unknown user on 01/17/2008)
Rating
ok, you say dont use @ under limitations, however your example uses @. so which is it? I dont see how you can write a stored proc without it.
I'll have to keep reading, but part 1 is especially basic.
 
Comment #96  (Posted by an unknown user on 01/31/2008)
Rating
What does the da object?
 
Comment #97  (Posted by miki on 02/03/2008)
Rating
www.vrilo.com/Zanimljivosti/189.html
 
Comment #98  (Posted by an unknown user on 02/05/2008)
Rating
it worked well for me and strait to the point.
 
Comment #99  (Posted by an unknown user on 02/12/2008)
Rating
I was trying to search, does access support stored procedure. if support then how to embed. This article meets my requirement. Thanks
 
Comment #100  (Posted by an unknown user on 02/15/2008)
Rating
how to write a producer in module in vb.net to connect ms-access
 
Comment #101  (Posted by an unknown user on 04/07/2008)
Rating
The above article should have addressed indetails about the where above code should have been written.
 
Comment #102  (Posted by an unknown user on 05/06/2008)
Rating
I learned something. Thanks
 
Comment #103  (Posted by an unknown user on 05/11/2008)
Rating
can you help me check statement below can store in SP in Access

sSQL = "CREATE PROC SpChangePwd(@Flag, @Userid VARCHAR(40), @Password VARCHAR(20) " & _
"AS " & _
"SET nocount on " & _
"DECLARE @IsExit Int " & _
"SET @IsExit = 1 " & _
"if @Flag = 0 " & _
" if not Exits(Select * From aspnet_Users Where Userid = UserID) " & _
"INSERT INTO aspnet_Users VALUES(userid, Password) " & _
"Else " & _
"SET @IsExit = 0 " & _
"if @Flag = 1 " & _
"UPDATE aspnet_Users SET userid = userid, password =password " & _
"WHERE Userid = Userid " & _
"if @flag = 2 " & _
"DELETE FROM aspnet_Users WHERE Userid = userid " & _
"SET nocount off " & _
"SELECT @IsExit;"

Please emai me at vuthanhpho@yahoo.com
 
Comment #104  (Posted by an unknown user on 05/24/2008)
Rating
your coding is very poor.som i request to you.you give coding in details.
 
Comment #105  (Posted by nick on 07/29/2008)
Rating
35zzsH hi! hice site!
 
Comment #106  (Posted by Andy Tabb on 07/30/2008)
Rating
comment from vwguy_65@yahoo.com
 
Comment #107  (Posted by an unknown user on 08/06/2008)
Rating
i finally found this information that i been looking for a long period of time.

Everything you need to know about your PC

enter101.blogspot.com
enter111.blogspot.com
 
Comment #108  (Posted by an unknown user on 08/27/2008)
Rating
I got what i was looking for
 
Comment #109  (Posted by Ken on 10/19/2008)
Rating
to get views having more featured areas. ,
 
Comment #110  (Posted by an unknown user on 11/23/2008)
Rating
Very informative
 
Comment #111  (Posted by an unknown user on 12/31/2008)
Rating
Perfectly mer my need
 
Comment #112  (Posted by an unknown user on 02/02/2009)
Rating
brief, thorough, useful
 
Comment #113  (Posted by an unknown user on 04/04/2009)
Rating
Good evening. If you want creative workers, give them enough time to play.
I am from Switzerland and learning to speak English, give please true I wrote the following sentence: "Global travel hotels airline tickets flights."

Best regards 8), Yorick.
 
Comment #114  (Posted by an unknown user on 04/27/2009)
Rating
First article I've found that showed how to create sp programatically both with and without parameters.
 
Comment #115  (Posted by an unknown user on 05/14/2009)
Rating
Thanks. You are great person.
 
Comment #116  (Posted by an unknown user on 06/10/2009)
Rating
nice
 
Comment #117  (Posted by an unknown user on 06/23/2009)
Rating
Greeting. It was enough to make a body ashamed of the human race.
I am from Spain and also now am reading in English, please tell me right I wrote the following sentence: "Compare prices on lamisil at cream for women from aol shopping."

Thank you very much 8). Mahala.
 
Comment #118  (Posted by an unknown user on 07/02/2009)
Rating
Enjoyed browsing through the site. Keep up the good work.
I am from South and too poorly know English, give true I wrote the following sentence: "Advances in pest control are making cat flea collar options more effective than ever before."

Thanks 8-). Talos.
 
Comment #119  (Posted by an unknown user on 07/02/2009)
Rating
Keep the good works comming.
I am from Azerbaijan and also am speaking English, tell me right I wrote the following sentence: "To clip the power cord to the battery, there are three metal screws; either the voice or chirping which is used by the car alarm as an armed or as disarmed confirmation."

With respect ;), Charlie.
 
Comment #120  (Posted by an unknown user on 07/03/2009)
Rating
Give please. I don't like composers who think. It gets in the way of their plagiarism.
I am from Togo and also am speaking English, please tell me right I wrote the following sentence: "When choosing a car alarm, buy the one that comes with or without the integrated immobilizer."

Thank you very much :-(. Nitika.
 
Comment #121  (Posted by an unknown user on 07/05/2009)
Rating
Sorry. People will buy anything that is one to a customer.
I am from Estonia and also now teach English, give please true I wrote the following sentence: "Our davie, fl dodge dealership always has a wide selection and low prices."

8-) Thanks in advance. Akiva.
 
Comment #122  (Posted by an unknown user on 07/05/2009)
Rating
Good Day. No great improvements in the lot of mankind are possible until a great change takes place in the fundamental constitution of their modes of thought.
I am from Guinea-Bissau and also am speaking English, tell me right I wrote the following sentence: "Ford dealers ankeny dodge dealers ankeny jeep dealers ankeny ford dealers iowa dodge dealers iowa jeep dealers iowa ford I twurled news beta."

:P Thanks in advance. Stockton.
 
Comment #123  (Posted by an unknown user on 09/04/2009)
Rating
Hey. Happiness is not a station you arrive at, but a manner of traveling.
I am from Honduras and learning to write in English, give please true I wrote the following sentence: "Girls are also made higher credit fees for system variants, since water stone municipalities are less other to be ineligible."

;-) Thanks in advance. Phedra.
 
Comment #124  (Posted by an unknown user on 09/04/2009)
Rating
Greeting. Hope is tomorrow's veneer over today's disappointment.
I am from Libya and learning to write in English, give true I wrote the following sentence: "SA¶renstam has criticized a attention of park theme debit transactions."

Thanks for the help 8), Ran.
 
Comment #125  (Posted by an unknown user on 09/04/2009)
Rating
Hello everyone. I feel about airplanes the way I feel about diets. It seems to me they are wonderful things for other people to go on.
I am from Northern and now study English, give true I wrote the following sentence: "Chase platinum mastercard, recent to its company on maximum versions, amex has automatically had lower benefits of college houses than only solutions."

Thanks 8). Vachel.
 
Comment #126  (Posted by an unknown user on 09/05/2009)
Rating
Hi everyone. The ornament of a house is the friends who frequent it.
I am from Angola and learning to speak English, give please true I wrote the following sentence: "Copenhagen also has a single card and card transaction."

THX :o, Zaltana.
 
Comment #127  (Posted by an unknown user on 09/08/2009)
Rating
How are you. Genius is one per cent inspiration, ninety-nine per cent perspiration.
I am from Syria and too bad know English, please tell me right I wrote the following sentence: "Together lyrics are asked."

With best wishes :-D, Kieran.
 
Comment #128  (Posted by on 10/11/2009)
Rating

 
Comment #129  (Posted by an unknown user on 11/03/2009)
Rating
Great article. Thank you. Just what I needed.
 
Sponsored Links