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
Hurricane Shutters
Phone Cards
Online Shopping
Shop
Remote Online Backup
Calling Cards
Rackmount LCD Monitor
Corporate Gifts
Compare Prices
Best Price
Auto Insurance Quote
KVM Switches
Dental Insurance
Logo Design




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
December 17, 2004
Fascinating Query Tricks
By Danny Lesandrini

I love writing VBA code but I am convinced that, many times what I am trying to accomplish can be done in a more efficient, graceful and elegant way using SQL queries.  Over the last few months, I have tried to develop my applications with this in mind.  The following article is a summary of problems I have been able to solve by using fascinating query tricks.  Here is an overview of what we will cover:

  • How to pass a variable parameter to a query calculation
  • How to add "<All Employees>" to a list of employee names
  • Use UNION query to add a Totals row to a dataset output

These common development tasks pop up all the time and some of these solutions I have been using for years.  They are the kind of things that are good to have in your toolbox.  If you don't already have a solution for these issues, download the demo application  for this article and store it with your stock code.

How to pass a variable parameter to a query calculation

VBA Solution:
The first tab of my demo form shows three different ways you can perform a price increase calculation.  In this example, I want to add a percentage to the price of a book.  The default is 10%, but this parameter should be adjustable.  The following shows two ways to accomplish this: one uses a VBA function and the other is strictly a query solution.

The following SQL Statement shows how the price could be calculated using a hard-coded value.  Of course, this is not very flexible or easy to adjust, so we want to make it dynamic.

  SELECT title_id, price, price * 1.10 AS Adj_Price FROM titles;

One way to make this calculation dynamic is to substitute a variable for the price increase percentage, except Access queries are not able to read variables, not even publicly declared ones.  The only way to pass a variable to a query is by means of a function that returns the variable, like this:

  SELECT title_id, price, price * FetchPricePct() AS Adj_Price FROM titles;

In this particular demo, the method FetchPricePct() returns the value of a public variable.  In order for this to fit into your code paradigm, you will need to have a function that also sets this public variable to some value.  Alternatively, you could put a reference directly to a control on a form, like this ...

  SELECT title_id, price, price * Forms!frmMain!txtPct AS Adj_Price FROM titles;

However, this creates a problem if the form is not open, or if the text box is empty, or if it doesn't contain a number.  You could, of course, write inline code to handle those exceptions in the query, but it gets kind of crowded ...

  SELECT title_id, price, price * 
         IIF(IsNumeric(Nz(Forms!frmMain!txtPct,1.1)), 
                 Nz(Forms!frmMain!txtPct,1.1), 1.1)AS Adj_Price FROM titles;

I have done this, and it works, but it's not pretty.  The IIF() function first checks to see if the value is numeric, substituting our default (1.10) for NULL, since NULL is neither numeric nor non-numeric.  If this test passes, then it uses the text box value but if it fails (the text "one point one zero" is not equal to 1.10) our default is supplied.  This kind of logic is better placed in a function which is easy to modify and even easier to reuse.  That is why I would discourage you from doing what is shown in the code snippet above.

Also, I've been known to do tricky things in the function, such as read values stored in the registry or search through open forms until I found one that has the particular ID I require.  That way the query is not tied to a specific form.  If  frmEmployee isn't open, maybe the EmplNo I seek can be found on a different form, such as frmTimeSheet.  Your functions can become very reusable.

There is one problem with this paradigm:  Access queries called from ASP web pages cannot resolve the source of the function.  They appear undefined to the ADODB layer and the query fails.  That brought me to my query based solution for this problem.

Query Solution:
What I really needed, I thought, was a table with a field that contained the price increase value.  If I could join this table to my Titles table, I could replace the function with a simple field value.  However, on what column could I join them?  No column, the answer turns out to be.  You create a Cartesian Product of the two tables by referencing both but assigning no kind of join.  The SQL for this solution looks like this:

  SELECT title_id, price, price * Pct_Increase AS Adj_Price 
  FROM titles, PriceVariable; 

There is a caveat: the tblPriceVariable table may have only one row.  If, for example, it contained two rows, then two records would be generated for every row in the Titles table.  Notice the right-most query result pane in the Figure 1 below and you will see what I mean.  Another thing you may notice from the image is that the tables using the Cartesian Product do not expose an "Add Record" line and the Add Record button is grayed out.  Because of the nature of the join, this recordset is not updateable.  For my ASP application, that was no problem, but if you need an updateable recordset, the Cartesian Product idea will not work for you.

 

Go to page: 1  2  Next  

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

Learn Tools & Techniques to Justify and Fund Your IT Investments. Download Complimentary Report Now!
IT in 2018: Download Free eBook By The Author Of "Does IT Matter?" Simple Registration Is Required.
Learn about expanding business opportunities for the reseller channel. Visit IT Channel Planet.
Quest Whitepaper: Improving Oracle Database Performance Using Real-Time Visual Diagnostics
HP eBook: Using Business Service Management (BSM) to Manage Your Business Applications


Latest Forum Threads
MS Access Forum
Topic By Replies Updated
Export a report into excel Irina_5220 4 May 9th, 01:50 PM
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