Free Newsletters:
DatabaseJournal  
DBANews
Database Journal
Search Database Journal:
 
HOME News MS SQL Oracle DB2 Access MySQL PostgreSQL PHP SQL Etc Scripts Links Discussion
internet.com

» HOME
» NEWS
» FEATURES
» SERIES
MS SQL
Oracle
MS Access
MySQL
DB2
» RESOURCES
Products
Scripts
Links
» DISCUSSION
» TECH JOBS

Marketplace Partners
Be a Marketplace Partner




internet.commerce
Be a Commerce Partner
Build a Server Rack
Logo Design
Car Donations
Hurricane Shutters
Memory
Remote Online Backup
Dental Insurance
Home Improvement
Desktop Computers
Promotional Products
Laptops
KVM Switch over IP
Promotional Gifts
Memory Upgrades




MySpace Joins eBay, Yahoo in Open Profile Push

News Corp. Unit Under Fire for Ties to Hacker

Are Non-PC Devices Hurting 'Net Innovation?

internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers


Linked Data Planet Conference & Expo

CA ERwin® Data Modeler Proven database design and modeling. Efficiently analyze, design and deploy effective database solutions. Whitepaper: Manage SQL Server Deployments
Try it free: CA ERwin® Data Modeler


Solaris 8 Migration Assistant
Rapidly move your Solaris 8 application environments to new systems running Solaris 10 with the Solaris 8 Migration Assistant. Reduce migration risk while taking advantage of increased performance, reliability and security of the latest SPARC hardware platforms and Solaris 10 OS. »

 
Sun Eco Innovation: Good for Business, Good for the Environment
A complete solution to help you optimize and refresh your datacenter while properly recycling equipment and eliminating eWaste, including money-saving promotions to lower hardware acquisition costs. »

 
Sun Eco Innovation: Power Calculators
Power consumption has increasingly become a priority in customer's minds when purchasing new systems or storage. Sun's Power Calculators provide data on power consumption of Sun products allowing IT managers to better plan the power requirements in the datacenter to achieve better energy and cost savings. »

 
Optimize the Web Tier: Consolidate to Get More Performance in Less Space and Lower Power Consumption
Expansion in the Web tier is generally accomplished by adding more servers whenever extra capacity is needed. As the pool of servers grows larger, however, the complexity of the environment can grow exponentially. »

Production Manager (hands on)
Aquent
US-MA-Cambridge

Justtechjobs.com Post A Job | Post A Resume
MS Access
January 21, 2005
Access Data Definition Language (DDL): Creating and Altering Tables On The Fly
By Danny Lesandrini

One of the first things an Access developer learns is how to write SQL Queries.  A simple request for data might look something like this:

   SELECT FullName, Address, Phone 
    FROM tblEmployee ORDER BY FullName

This type of query uses Data Manipulation Language (DML).  While this example does not perform any great manipulation of the data, some very clever calculations are possible.  The SQL language is powerful indeed.

However, once you have gotten a handle on DML, you will want to explore the world of DDL, Data Definition Language.  This too is part of the SQL language and can be run from an Access query, or through VBA code, but unlike DML, these commands do not return a result set.  DDL is used to create and alter database objects, such as tables.  First, let's see how this is done and then consider some scenarios where this technique will save you time and in some cases, a lot of work.

Help Yourself:  Where to find answers

Before we look at some examples, it is worth revisiting the old "teach a man to fish" analogy.  Truth is, if I do not use a particular code technique frequently, I tend to forget the syntax.  While I am sure a comprehensive explanation exists in one of the mammoth technical volumes resting on my bookshelf, it is easier to simply search the Internet for the answer.  My favorite resource is the advanced search page at Google Groups.

In fact, I find this resource to be so valuable, I have saved the following hyperlink to my Internet Explorer LINKS toolbar:   Access GoogleNewsgroup Search   (This hyperlink pre-populates frequently used fields, saving me time.)  A quick search for 'DDL' in the Access related newsgroups yielded a plethora of results.  What follows in this article was culled from suggestions found there, as well as from an article from the Microsoft Knowledge Base:  'How to' write Access DDL  that I found while searching the Google results.

The scripts used in this article have been collected into a demo database that is available for download.

Create a Table

For starters, let's consider the example provided by Microsoft in the KB Article mentioned above.  This script shows, in a nutshell, how to create a table with one column of each type of field, including AutoNumber, which is only intuitive if you remember that in Access 2.0, the AutoNumber was called a COUNTER field.

   CREATE TABLE TestAllTypes
   (  MyText       TEXT(50),
      MyMemo       MEMO,
      MyByte       BYTE,
      MyInteger    INTEGER,
      MyLong       LONG,
      MyAutoNumber COUNTER,
      MySingle     SINGLE,
      MyDouble     DOUBLE,
      MyCurrency   CURRENCY,
      MyReplicaID  GUID,
      MyDateTime   DATETIME,
      MyYesNo      YESNO,
      MyOleObject  LONGBINARY,
      MyBinary     BINARY(50)
    )

The process to create a DDL query is a little different from what you might be used to.  Begin in the normal way, by choosing New Query from the Query window, but when prompted, do not add any tables.  You are then presented with the QBE (query by example) grid with no tables. Select Data Definition from the Query | SQL Specific menu to continue.

Selecting Data Definition will take you to a very plain, Notepad-like interface where you can paste or type in your DDL SQL script. Save the query and select Run from the Query menu to execute the script. When you run this kind of query, Microsoft Access displays the following warning:

If you know what you are doing, and want these warnings to go away, there is an application option that allows you to turn off the confirmation message for Action Queries.  Choose Options from the Tools menu and go to the Edit/Find tab.  Deselect the checkbox next to Action Queries.  Alternatively, you can toggle this option from the Immediate window using the following VBA command:

     DoCmd.SetWarnings False

After running the script, open up the table in design view.  Notice how each field was created with its specific type and though the screen shot does not display it, the TEXT field is indeed a 50-character field, just as we requested.

 

It is not at all difficult to add an index, or a unique index, to a column.  For the example above, the following script puts an ordinary index on the DateTime field and a unique index on the Text field. (Note: Unlike SQL Server, DDL scripts in Microsoft Access must be run one at a time.)

    CREATE INDEX MyDateTimeIndex ON TestAllTypes ([MyDateTime] ASC)

    CREATE UNIQUE INDEX MyTextUniqueIndex ON TestAllTypes ([MyText] ASC)
    
    DROP INDEX MyTextUniqueIndex ON TestAllTypes  

Note from the last script above that you can also delete, or DROP, indexes or entire tables.  However, if you want to change the column structure of a table, the syntax changes a bit.  Rather than simply dropping a column, you need to perform an ALTER TABLE command.

ALTER TABLE TestAllTypes DROP COLUMN MyBinary
    
    ALTER TABLE TestAllTypes ADD COLUMN ExtraInfo Text(255)

When to use DDL

There are several scenarios where DDL might be the perfect solution.  Here are some that I've encountered over the years:

  • Create and delete temp tables for reports or other calculations.
    (Caution: will cause database file bloat.  I have seen this done where the temp
      tables are created in a temp mdb file that is created, loaded, used and deleted.)
  • Maintenance scripts used to push new tables out to client applications.
  • Used in conjunction with DAO to loop through a table's fields, check their properties
    and create a new table with proper naming, data types and sizes.
  • If you are ambitious, you could write a script to recreate your entire database.

As for that last point, I am surprised that someone has not written a tool that will analyze your Microsoft Access MDB file and build all the scripts necessary to recreate the tables, indexes, constraints and maybe even load the data by means of SQL DDL.  Perhaps someone has created such a tool, but I searched for it last year without success.  If anyone knows of such a utility, please email me the lead.

There are, of course, aspects of DDL we did not touch on in this brief article.  It is a fascinating technology and once you start playing with it, you will no doubt see its value.

» See All Articles by Columnist Danny J. Lesandrini

Tools:
Add databasejournal.com to your favorites
Add databasejournal.com to your browser search box
IE 7 | Firefox 2.0 | Firefox 1.5.x
Receive news via our XML/RSS feed

MS Access Archives

Whitepaper: Enterprise Information Integration--Deployment Best Practices for Low-Cost Implementation
Learn about expanding business opportunities for the reseller channel. Visit IT Channel Planet.
Download: Solaris 8 Migration Assistant. Run Solaris 8 apps on the latest SPARC systems and Solaris 10.
Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers. Sponsored by HP, Citrix, and Intel.
IT in 2018: Download Free eBook By The Author Of "Does IT Matter?" Simple Registration Is Required.


Latest Forum Threads
MS Access Forum
Topic By Replies Updated
Export a report into excel Irina_5220 2 May 9th, 08:48 AM
Table Property Question barlowr70 0 May 6th, 10:51 AM
Compile MS Access Database samson 1 May 1st, 03:28 AM
How to connect MS-Access with c++ rockys111 0 April 30th, 01:36 AM







JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: HyperV-The Killer Feature in WinServer ‘08
Avaya Article: How to Feed Data into the Avaya Event Processor
Microsoft Article: Install What You Need with Win Server ‘08
HP eBook: Putting the Green into IT
Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
Avaya Article: Setting Up a SIP A/S Development Environment
IBM Article: How Cool Is Your Data Center?
Microsoft Article: Managing Virtual Machines with Microsoft System Center
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Video: Are Multi-core Processors Here to Stay?
On-Demand Webcast: Five Virtualization Trends to Watch
HP Video: Page Cost Calculator
Intel Video: APIs for Parallel Programming
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Sun Download: Solaris 8 Migration Assistant
Sybase Download: SQL Anywhere Developer Edition
Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
Red Gate Download: SQL Compare Pro 6
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
IBM Article: Collaborating in the High-Performance Workplace
HP Demo: StorageWorks EVA4400
Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES