Toad For Data Analysts: User Guide
Toad For Data Analysts: User Guide
User Guide
2.6
2010 Quest Software, Inc. ALL RIGHTS RESERVED. This guide contains proprietary information protected by copyright. The software described in this guide is furnished under a software license or nondisclosure agreement. This software may be used or copied only in accordance with the terms of the applicable agreement. No part of this guide may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying and recording for any purpose other than the purchasers personal use without the written permission of Quest Software, Inc. The information in this document is provided in connection with Quest products. No license, express or implied, by estoppel or otherwise, to any intellectual property right is granted by this document or in connection with the sale of Quest products. EXCEPT AS SET FORTH IN QUEST'S TERMS AND CONDITIONS AS SPECIFIED IN THE LICENSE AGREEMENT FOR THIS PRODUCT, QUEST ASSUMES NO LIABILITY WHATSOEVER AND DISCLAIMS ANY EXPRESS, IMPLIED OR STATUTORY WARRANTY RELATING TO ITS PRODUCTS INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL QUEST BE LIABLE FOR ANY DIRECT, INDIRECT, CONSEQUENTIAL, PUNITIVE, SPECIAL OR INCIDENTAL DAMAGES (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF PROFITS, BUSINESS INTERRUPTION OR LOSS OF INFORMATION) ARISING OUT OF THE USE OR INABILITY TO USE THIS DOCUMENT, EVEN IF QUEST HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Quest makes no representations or warranties with respect to the accuracy or completeness of the contents of this document and reserves the right to make changes to specifications and product descriptions at any time without notice. Quest does not make any commitment to update the information contained in this document. If you have any questions regarding your potential use of this material, contact: Quest Software World Headquarters LEGAL Dept 5 Polaris Way Aliso Viejo, CA 92656 www.quest.com email: [email protected] Refer to our web site for regional and international office information. Trademarks Quest, Quest Software, the Quest Software logo, Benchmark Factory, LiteSpeed, Spotlight, SQL LiteSpeed, SQLab, Toad, T.O.A.D., Toad World, vOptimizer Pro, vSpotlight, and vToad are trademarks and registered trademarks of Quest Software, Inc in the United States of America and other countries. Other trademarks and registered trademarks used in this guide are property of their respective owners.
Table of Contents
Introduction Understand Toad's Workflow Connect Create ODBC Connections Understand Toad Connections Understand Determine the Best Method to Locate Objects Object Explorer Filter Databases and Objects Scenario:Understand a Table Using the Database Explorer Search for Objects Scenario:Create an ER Diagram to Use as a Query Template Browse Data in Related Tables Query Scenario:Visually Build a Query Create Heterogeneous Queries Reverse Engineer Queries Build a Subquery About Editing SQL Editor Shortcut Keys View Result Sets Compare Differences in Data Export Data with One Click Export Share Excel Linked Queries 5 5 7 7 8 10 10 10 11 13 16 17 19 21 21 23 25 29 31 32 35 37 37 39
Report Scenario:Create a Toad Data Report Manage Reports Publish and Share Reports Automate Scenario: Automate a Query and Email the Report Automate Tasks Use Database Automation Activities Use File Automation Activities Use System Automation Activities Use Variables in Automation Execute Automation Scripts Appendix: Contact Quest Contact Quest Support Contact Quest Software About Quest Software Index
42 42 48 58 61 61 63 65 68 71 75 82 83 83 83 83 84
1
Introduction
Understand Toad's Workflow
Toad for Data Analysts is built on the premise that nearly every reporting project gores through some form of the following steps at some point: Understand, Query, Report and Automate. There are times when you omit one of these steps, but they represent the general flow of a standard reporting project.
Understand
This first step is often overlooked, yet it may be the most important step in the process of your project. Many times, users connect to a data source and just start creating queries blindly. While it may feel more productive to dive right in, its a false sense of accomplishment. The best queries begin with a clear understanding of the data source you are connected to. This is because if you understand the data, objects and their relationships to each other (if such relationships exist), then you can build informed queries that are effective and more optimized than you could without this understanding. Toad for Data Analystssupports the following methods for understanding:
l
ER DiagrammerGives you a high-level, visual representation of an object and those objects which may be related to it. Database ExplorerGives you a more in-depth and detailed view into the object so you can see column information, the data itself, relationships and more.
Query
This is the heart of Toad for Data Analysts and probably the most time consuming part of your project. Once you have gained a clear understanding of the data source you will query from, you can begin creating your query. Toad for Data Analystssupports the following methods for understanding:
l
Query BuilderBuilds the query for you using a visual interface. Whether you are new to databases and unfamiliar with the SQL language or a seasoned veteran, the Query Builder saves you time. And regardless of the database you connect to, the Query Builder is the same, for all database platforms so you do not have to remember all of the nuances of how the SQL language differs between database platforms. SQL EditorFor the coders out there, Toad for Data Analystsprovides the same powerful SQL Editor that is found in the rest of the Toad family of products. Regardless of your skill-levelor level of motivationyou have all the tools you need to create your queries easily and quickly.
Report
The next step in the process is reporting. Naturally, once you get the information you want with your query, 9 times out of 10 you want to share that information. Whether you need to share a statistic in an email or create a beautiful multi-page PDF, Toad for Data Analysts can help. It supports several methods of reporting: One-Click Export to Microsoft Excel, pivot tables, charts, and Toad Reports (Toads own banded report designer). The One-Click Export feature takes whatever you have in the data grid, whether it is a query result or the data in the Database Explorer, and exports it to a specific Microsoft Excel format in a single click. A handy, time-saver, One-Click Export can even automate the creation of refreshable Microsoft Excel documents. Pivot grids, charts and general banded reports are designed with the Toad Reports interface and can be saved to a variety of formats. You can also take a shortcut and create a quick pivot table and chart right in the results grid of a Query Builder or SQL Editor window.
Automate
The final piece of the process is automation. With your query written and your report complete, save time and automate the process. Many times we find ourselves doing the same things over and over. Toad for Data Analysts goes beyond standard query and reporting tools to reduce this redundancy. Using an intuitive, task-oriented, timeline approach, Toad for Data Analysts takes all of those mindless, repetitive tasks and does them for you. You can create entire workflows that encompass connecting, importing/exporting, executing scripts, running queries, building reports and distributing those reportsyou can even add in conditional logic. With a solid automation workflow built, schedule it to run on any schedule. Now your reporting tasks will take care of themselves, automatically.
2
Connect
Create ODBC Connections
The purpose of the ODBC provider is to offer basic connection and querying capabilities to any database that supports an ODBC 3.0 or later driver. For a list of databases tested with the ODBC provider, see the Release Notes. This form of connectivity allows connections to databases such as Teradata, Netezza, IBM iSeries, and Ingres. Because this form of connectivity is generic, it is not full-featured and may not be as robust as the fully exploited providers for databases that use a native provider.
Scenario
You need to create an ODBC connection to an Oracle 11g database. To create an ODBC connection 1. Click on the toolbar (ALT+F+N+O).
2. Select ODBC from the Group list box. 3. Click 4. Click Add. 5. Select an ODBC driver from the list, and click Finish. Scenario: Select the ODBC driver provided by Oracle. The Microsoft ODBC for Oracle driver has less functionality than the driver provided by Oracle. 6. Specify the configuration properties required for the database. Scenario: If you have an Oracle database with Unicode data, make sure to select Force SQL_WCHAR Support on the Workarounds tab. If you do not, you will not be able to see the data. 7. Review the following fields on the Create New Connection window: Data source name User Password Select the type of data source you want to connect to from the list. Enter the user name to use when connecting. Enter the password to use when connecting. Tip: After connecting, you can set a master password to further secure your connection in Tools |Options|Environment | Password. in the Data Source Name field.
Database
Specify the location of the database schema. Click to create a temporary connection and display available schemas in the dropdown list. Specify the following connection options. Displays they type of data source selected.
Displays the ODBC driver associated with the data source. Enter the connection string. Edit the nickname you want to display in the Connection toolbar, status bar, and document windows, if needed. Select or create a category if you want to color code Editor tabs for a specific connection. This can help differentiate between development and production databases. You can also set an option to color code the Object Explorer pane and object editor windows (Create, Alter, Drop, etc.).
8. Click Connect to save the connection and immediately connect to the database. or Click Save to save the connection without connecting to the database. Tip:Connections are stored in the connections.xml file and can be found by clicking the Application Data Directory link in Help |About.
To view the number of actual database connections that exist for a Toad connection and how many of those database connections are active, place the cursor over the
connection in the Navigation Manager or the Connection toolbar (illustrated in the following example).
You can view the progress of statements executing in the background in a progress bar located on the lower right side of the status bar. To cancel a script's execution, click the progress bar to display the Background Processes window.
(DB2 and Oracle only) If your database supports executing multiple queries simultaneously on a shared connection, the query is placed in a queue and executes as soon as the current operation completes. If your database does not support executing multiple queries on a shared connection, a dialog prompts you to either permanently associate the window with a new database connection, cancel the previous operation, or add the query to a queue until the current operation completes, and the execute it. If you place multiple queries in the queue, each one executes in the order that it was added to the queue.
Note: Although you can share a database connection, any commits apply to the selected window only.
3
Understand
Determine the Best Method to Locate Objects
Toad offers a number of features to assist you in locating objects. The following table provides guidelines based on typical use cases: If you know the.... Column name, but do not know the table name String of DDL for an object Dependency for an object Uses and Used By tabs in the Database Explorer, and then drill-down to the object from there Filter feature in the Object Explorer Use this... Use Object Search
Object Explorer
You can view database objects for the current connection with the Object Explorer. This feature is useful for dragging and dropping database objects into an open Editor, Query Builder, or other document window. To open the Object Explorer 1. Click on the View toolbar.
2. Review the following for additional information: Schema (first field) Object Filter (second field) Select the schema you want to view. You can filter the list of schemas that display. See "Filter Databases and Objects" (page 11) for more information. You can quickly set a filter in this field. To do so, enter a name or partial name of an object and press ENTER. Any advanced object filters you set display in this field. You can also perform advanced filtering based on case sensitivity, statistics, or other options. See "Filter Databases and Objects" (page 11) for more information.
11
Tip:You can enable an option to filter using regular expressions in Tools |Options |Explorer |General. Note: For tables and views, the columns, data types, and comments display at the bottom of this window. Tips:
l
to move
To locate objects including procedures, functions, views, variable names and comments in an object's source code, use Object Search. See "Search for Objects" (page 16) for more information. To use a different method to select objects such as tabs, drop-downs, or a tree view, click . To generate reports, export data, create SQL statements, version control objects, or send objects to the Project Manager, SQL Modeler, or Master Detail windows, rightclick the objects and select an option. To open the Background Processes window and cancel a query, click the progress bar at the bottom of the window.
Quick filterApplies to the current schema, or objects in the current schema only. Any unnamed filter you set is in effect the next time you open Toad Unnamed filterApplies to the current schema, or objects in the current schema only. Any unnamed filter you set is in effect the next time you open Toad. Named filterApplies to any database connection for the current database provider. Any named filter you set is in effect the next time you open Toad. Note: If you rename a table that has a filter defined, it results in an orphaned filter. Orphaned filters are automatically removed unless you used a tool other than Toad to remove them.
A filter is associated with a specific list of objects from a specific database. Consider the following guidelines when setting filters:
l
A filter defined for a set of objects such as tables on one specific database connection does not apply to a list of objects for another database connection. A filter defined for a list of tables on one schema in the database does not apply to
12
A filter set for a specific schema or object is applied when altering objects, using the SQL Editor, Master Detail Browser, etc., for that schema or object. Tip: To apply any filters you set to the code completion list in the editor, select the Apply explorer filters checkbox in Tools |Options | Editor |Code Completion.
To set a quick filter Enter text to use for filtering in the field below the database/schema name in the Object Explorer:
To set a named filter 1. Click beside the database or object field in the Object Explorer.
2. Define criteria for the filter in the Properties tab. 3. Select the SQL tab and select the Enable custom SQL checkbox to create a custom filter based on criteria you specify. 4. Select the Preview tab to view a list of databases or objects that meet your filter criteria before applying the actual filter. 5. Enter a name for the filter if you want to use the filter for other database connections and click Icon . Description A filter has not been set so all databases/objects display. A filter has been set.
13
6. If you set a named filter, you can click the arrow beside the remove the filter:
icon to apply or
Tips:
l
To export a named filter or any filters associated with the current connection, click the arrow beside the icon and select Export Filters.
Click
in the Explorer toolbar to clear all database, object, and data filters.
14
3. View information for the following: a. Click the Indexes tab and view the index information. b. Click the Primary Keys and Foreign Keys tabs to view relationships. 4. Click the Data tab. 5. Place the cursor over the LAST_NAME column, click , and select Acton.
The only row that now displays is the one with Acton as the last name. 6. Click to the right of the LAST_NAME column again and select All to clear the filter. 7. Click the CONTACT_ID column to sort the rows in ascending or descending order. 8. Click in the top left of the Data tab.
9. Create the following filter in the Where Clause tab: CONTACT_ID > 2000 The filter string displays at the bottom on the grid. Click to remove the filter.
15
10. Select a row of data in the grid. Notice that the row number changes in the bottom right of the status bar:
11. Under the SEX column, right-click the area below the last row in the grid that says "Right-click to add column totals" and select Count. The total number of rows that have either a M or F value display. 12. Click to the right of the SEX column and select F. The count value updates based on the new filter. 13. Click to the right of the SEX column again and select All to clear the filter.
14. Select the SEX column header and drag it the area above the columns that says "Drag a column header here to group by that column":
You can expand each group to view the row data. 15. Switch the default view: a. Right-click within a group or row on the grid and select Show |Card View. b. Scroll through some records. c. Click Customize in the Card View window. d. Click Filter beside the ADDRESS_IDcolumn and select 100. Notice how the card view is filtered, but not the grid view. e. Close the Card View window. 16. Edit a row: a. Select a row in the FIRST_NAME column and edit the value. b. Press ENTER to update the row.
16
c. Go to the BIRTH_DATE column and use the date picker to change the date. Each data type have an appropriate editor. Note: If you are using Oracle or a database that does not have auto commit on, you will need to press Commit at the left hand bottom of the window. 17. Update the number of rows in in the data: a. Select Tools | Options | Database | General from the menu. b. Enter 50 in the Number of rows to initially fetch in data tab. c. Click OK. d. Press F5 in the data grid. Notice the bottom right status bar now says "1 of 50 (scroll for more)". The option you set controls the number of rows fetched in the Data tab. e. Click the scrollbar and hold down to retrieve more. f. Right-click the grid and select Read All Rows.
Names of objects for a string. Text in objects that include source code, which typically includes procedures, functions, triggers, data types, and views. However, the database provider determines which objects include source code. Variable names and comments in the object's source code. Column names for tables and views.
2. Specify search criteria and click Search. Note:To append additional search results to the current search, click Append instead. If you click Search, new results replace the previous search results in the data grid. Tips:
l
To remove objects from the search results, right-click the objects in the data grid and select Remove Items. This is useful if you want to narrow the list of results to
17
relevant objects. Note: This does not remove the objects from your database.
l
To create a DDL script from the search results, right-click the data grid and select Create DDL Script. You can then paste the results into the Editor. To perform any actions available for the object, such as creating, altering, dropping, exporting, and generating reports or SQL, right-click the results in the data grid and select an option.
3. Drag the CONTACTtable in the Object Explorer and drag it to the Diagram pane.
4. Right click the Diagram pane and clear Show Dependencies to hide the Referenced
18
5. Right-click the ORDERS table and select Notes. 6. Enter the following note in the window for other users: The shipping and billing ADDRESS_ID foreign key relations are not needed in most queries and should be hidden when building a query. 7. Because it is against company policy to display sex and a home phone number in reports, right click on each of these columns in the CONTACT table and select Hide Column. Tip:If you have a large number of columns you need to hide, you can right-click a table and select Manage Hidden Columns to quickly select them from a list. 8. Click Add to Project from the wizard bar at the bottom of thewindow and enter ERDiagram_Test asthe name for the file. This adds the file to the current project in the Project Manager under a Diagrams folder. 9. Close the ERDiagram window and open the Project Manager window. 10. Expand the Diagrams folder and double-click ERDiagram_Test to reload the file in a new ERDiagram window. 11. To share your project, hidden columns, and notes with colleagues, complete the following: a. Select Tools | Options | Environment |Network Share from the menu, and navigate to a shared drive. This is where the Project Manager file will be stored. b. Select Database |Cache from the open Options window and set the folloiwng options: Object An notation Cache Share object Description Select this checkbox and enter a shared drive
19
location where users can access this file. Select this checkbox.
c. Provide the location of the Network Share and Object Annotation Cache settings to colleagues who need to use this diagram.
A line between tables indicates any existing relationships between the selected tables. At least one parent table (table without any join arrows pointing to it) must be added to the window or an error message displays when returning results.
3. Join Columns. 4. Select the checkbox beside each column you want to include. Note: Any columns included in a join are automatically included in the results. 5. Click (F9) to retrieve data for the parent table initially. To view data in a child table, click + to the left of each row. or Click to retrieve data in the parent and child tables. If there is more than one child table, a tab displays for each child table.
20
Edit the data and commit your changes to the database. Right-click the data grid and select Send To | option to add the data to a report, chart, or pivot grid.
Tips:
l
Click
Select the parent table from the drop-down list in the toolbar to view data for a parent table if there are multiple parent tables. Click X on the table you want to remove in the Diagram pane to remove a table and any conditions (e.g., join, where clause) associated with the table.
4
Query
Scenario:Visually Build a Query
The Query Builder enables you to create a query without writing or editing SQLstatements. Even if you are familiar with SQL, the graphical interface makes it easier to create relationships and visualize the query. Note: This procedure does not cover all of the possible steps of visually building a query. It only covers the steps required to build a query for the scenario.
Scenario
Your company wants to improve its global sales, starting with countries where it has a customer base but generally low sales. You need to create a query that identifies countries with less than $500,000 in sales for each of the last four fiscal years. Note: This scenario uses the SH (Sales History) sample schema that comes with Oracle 10g so you can follow the procedure. To visually build a query based on this scenario 1. Connect to the database and click Query. 2. Select the SH schema in the Object Explorer. 3. Drag the following tables from the Object Explorer to the Diagram pane: TIMES, SALES, CUSTOMERS, and COUNTRIES. Tips:
l
Select Query Builder |Arrange Tables (ALT+Q+A) to have Toad arrange the tables in the Diagram pane. You can also press CTRL and select all of the tables in the Object Explorer, and then drag them into the Diagram pane. Toad automatically arranges the tables.
4. Add the following columns to the query by selecting the checkbox beside each column: Column COUNTRY_NAME FISCAL_YEAR Table COUNTRIES TIMES
22
Column AMOUNT_SOLD
Tip: To view details for a table in the Diagram, click selected, details for the last selected table display.
5. Complete the following steps to group the data and sum the sales: a. Select the Group By field in the COUNTRY_NAME column, and then click +. The Group By field is in the Criteria pane, which is below the Diagram pane. b. Select the Group By field in the FISCAL_YEAR column, and then click +. c. Select the Aggregate Function field in the AMOUNT_SOLD column and select Sum. This sums all of the sales per fiscal year per country. Note: If you select a group by clause or aggregate function for a column, the rest of the columns in the query must also have a group by clause or aggregate function. 6. Complete the following steps to select the fiscal year range: a. Select the Where Condition field in the FISCAL_YEAR column and click The Where Condition window displays. b. Select BETWEEN in the Operators field. c. Select 1998 in the first Constant field. d. Select 2001 in the second Constant field and click OK. Note: The SH schema does not have current data. The 1998-2001 years provide the best data for the purposes of this scenario. 7. Complete the following steps to select countries with less than $500,000 in sales: a. Select the Having Condition field in the AMOUNT_SOLD column and click . The Having Condition window displays. b. Select < in the Operators field. c. Select Sum in the Aggregate field. d. Enter 500000 in the Constant field and click OK. 8. Select Ascending in the Sort field of the COUNTRY_NAME and FISCAL_ YEAR columns. .
23
9. Click
The query results display in the Results tab. See "View Result Sets" (page 35) for more information.
10. To save the query, right-click the Query Builder tab and select Save File. You can save a query and any results sets in a Toad editor file (.tef). This file format is useful for building scripts that have large result sets that you do not want to continue executing or for saving results when you have not finished building a script.
24
Description A heterogeneous query may take longer to execute then a query against a single database because result sets from each database are retrieved and combined to generate a single result set. Also, ODBC data retrieval is slower than using a native database client connection. You can select a specific driver to use for heterogeneous queries when connected to a native Oracle, SQLServer, MySQL, or Sybase database provider in Tools |Options | Database | NativeDatabaseProvider. This is a global change that affects all connections that use this provider. To specify an ODBC driver for a single connection 1. Right-click the connection in the Navigation Manager window and select Properties. 2. Select the Advanced tab and then specify a driver.
You can create inner joins, cross joins, left outer joins, and right outer joins in heterogeneous queries. Note: Full outer joins are not supported.
Subqueries are not supported Unions are not supported DB2 client connections are not supported Multiple Excel connections are not supported Combining Access and Excel queries is not supported Result sets cannot be edited
You cannot create a heterogeneous subquery. If you have an existing subquery, you cannot create a heterogeneous join. You cannot create a heterogeneous query that contains a UNION operator. You cannot create a heterogeneous query from a DB2 client connection. Instead, connect to the DB2 database using an ODBC connection, and then create the query. You cannot create a heterogeneous query between two or more Excel connections. You cannot create a heterogeneous query between an Access and Excel connection. You cannot edit result sets.
Tip: You can determine the connection associated with each table or view, by placing the cursor over the table name in the Diagram pane, similar to the following:
25
Quote identifiers
26
Excel support
Copying a generated query and attempting to reverse engineer that query results in an error. This issue occurs because the parser defaults to Oracle syntax, which does not understand quotation marks for fully qualified object names. To avoid this issue, clear the Use fully qualified object names and Use fully qualified column names checkboxes in Tools |Options |Database |Query Builder or manually edit the query. When sending a query from the Editor to the Query Builder, Toad automatically uses ANSI joins. If you use Where clause joins, click to disable ANSI joins. This converts the statement to the correct join. Description If you send a query that contains a Where condition from the editor to the Query Builder, it displays in a Global Where clause bubble on the Diagram pane instead of in the Where Condition field in the Criteria grid. You can double-click the Global Where Clause bubble in the Diagram pane, or can click to edit it.
Where Condition Where condition does not display in the Criteria grid after sending it to the Query Builder from the Editor
You can also use the Where condition fields in the Criteria grid to add new Where conditions. Although they display in the grid, they are added to the Global Where clause in the Query tab. Where condition created in the Criteria grid of the Diagram tab disappears If you define a Where condition in the Criteria grid and edit any part of the query in the Query tab, the Where condition is removed from the Criteria grid and placed in a Global Where Clause bubble. You can double-click the Global Where Clause bubble in the Diagram pane, or can click to edit it.
27
Having Condition Having condition does not display in the Criteria grid after sending it to the Query Builder from the Editor
Description If you send a query that contains a Having condition from the editor to the Query Builder, it displays in a Global Having clause bubble on the Diagram pane instead of in the Having Condition field in the Criteria grid. You can double-click the Global Having Clause bubble in the Diagram pane, or can click to edit it.
You can also use the Having condition fields in the Criteria grid to add new Having conditions. Although they display in the grid, they are added to the Global Where clause in the Query tab. Having condition created in the Criteria grid of the Diagram tab disappears If you define a Having condition in the Criteria grid and edit any part of the query in the Query tab, the Having condition is removed from the Criteria grid and placed in a Global Having Clause bubble. You can double-click the Global Having Clause bubble in the Diagram pane , or can click Query Builder Diagram Tab Comments and code regions removed after making changes in the Diagram tab Same column cannot be used in the criteria grid Execute with different query in the Diagram and Query tabs Description When reverse engineering a statement from the editor or the Query tab and switching to the Diagram tab, if the statement contains a block comment or code region and you make a change in the Diagram tab, the comment or code region is removed from the statement. You cannot use the same column more than once in the criteria grid. Even if you create a separate alias for the second use of the column, that column is created as a calculated field If the query in the Diagram tab is different than the query in the Query tab, executing the query executes the SQL in the Query tab instead of the Diagram. to edit it.
28
Save with different query in the Diagram and Query tabs To reverse engineer a query
The Query Builder saves both the statement and diagram in the same file. The contents of the statement and diagram can be different without losing changes.
1. Right-click a statement in the Editor, and select Send to Query Builder.See "About Editing SQL" (page 31) for more information. or Click in the Query Builder to send a statement to the Editor. Skip the remaining steps and continue to edit the query. See "About Editing SQL" (page 31) for more information. Troubleshooting:If the query cannot be modeled in the Diagram tab, a message displays and the statement opens in the Query tab. This usually occurs because the graphical diagram cannot support some functionality in the statement. You can view an explanation for this in the Output window or by hovering over the syntax with a red underline ( ) in the Query tab. To continue, correct the error and click apply the change and open the Diagram tab. 2. Continue to build your query visually using the diagram. 3. Select the Query tab and make any additional edits. Indicators for an edited statement are as follows: Inserted lines Modified or removed lines Modified characters Use the toolbar in the lower-right corner of the Query tab to modify the color used for each indicator. Caution: If you manually enter or update the statement in the Query tab, you must click to model the query in the Diagram tab. If you do not do this and make additional changes in the Diagram tab, any changes you made in the Query tab are lost. 4. Click to execute the query. to
29
Build a Subquery
Scenario
You need a report that lists the customers whose contacts are in a specific region specified by the user. Note: This topic focuses on information that may be unfamiliar to you. It does not include all step and field descriptions. To build a subquery 1. Connect to the Toad Sample (Access) database in the Navigation Manager. 2. Click on the toolbar.
3. Drag the CUSTOMER table to the Diagram pane. 4. Add the following columns to the query by selecting the checkbox beside each column:
l l
CUSTOMER_ID CUSTOMER_NAME beside the Where Condition for the CUSTOMER_ID column.
5. Add the subquery: a. Click b. Select the INoperator from the list and click Subquery. The diagram pane now applies to the subquery. c. Drag the following tables to the Diagram pane and select the following columns: Select this table... ADDRESS CONTACT Select this column... REGION_ID CUSTOMER_ID
d. Click beside the Where Condition for REGION_ID column and set the value as follows: Operator Constant = 1
30
7. Because you can't remember what region 1 covers, do the following: a. Select the REGION_ID checkbox in the ADDRESS table. b. Right-click REGION_ID and select Find Lookup Table. c. View the value for region 1 and click Apply Lookup Value. d. Click beside the Where Condition for REGION_ID column. Notice that the description of the region now displays:
9. To change the query to use a bind variable so you can enter a value to change the query, complete the following steps: a. Click beside the Where Condition for REGION_ID column.
b. Replace your constant with :a . The colon is a symbol for a bind followed by the bind name. c. Click , and enter a value when prompted.
31
Note: You can query the worksheet from the Editor by entering a dollar sign ($) followed by a cell range to limit the results similar to the following statement:
Select * from (MyWorksheet$A1:C10)
You can also query the entire worksheet by entering a dollar sign ($) after the worksheet name; however, this returns empty rows and columns in the worksheet. 2. Use the following to help enter SQL:
l l l l l l l
Code completion Code regions Code snippets SQL recall Add/remove application code Object lookup (Describe) Macros to record keystrokes to format the code. to validate the syntax.
3. Click
Note: Toad undoes any changes to the object and data in the database after executing the script (notice that the Result Sets tab is empty). To modify the object and data, you need to execute the script. 5. Click Tips:
l
Toad automatically saves a backup copy of any modified editor file in the Application Data Directory to avoid losing your work. When you restart Toad after an unexpected close, Toad checks the timestamp on the backup file against the original file, and opens the file that has the latest timestamp. The document recovery option is in Tools | Options | Environment | General.
32
You can save the current connection, SQL script, executed results,filters, and group execute connections/results (if enabled) in a Toad editor file (.tef). This file format is useful for building scripts that have large result sets that you do not want to continue executing or for saving results when you have not finished building a script.
33
SHIFT+ESC ESC Case CTRL+L CTRL+U Clipboard CTRL+C CTRL+X CTRL+V CTRL+SHIFT+V Code Completion CTRL+PERIOD Comment CTRL+MINUS CTRL+SHIFT+MINUS Cursor HOME CTRL+HOME END CTRL+END CTRL+] or CTRL+[ Debugger CTRL+DELETE SHIFT+F12 F7 SHIFT+F7
Sets a position indicator at the cursor location Pops the position indicator Description Converts the selected text to lowercase
Converts the selected text to uppercase
Description Copies the selected text to the clipboard Cuts the selected text for pasting in the clipboard Pastes text from the clipboard Pastes items from the Clipboard Ring Description Display code completion list Description Comments the selected line Uncomments the selected line Description Moves the cursor to the beginning of the line Moves the cursor to the beginning of the file Moves the cursor to the end of the line Moves the cursor to the end of the file Moves the cursor to the matching bracket Description Set a null value for a start parameter Step from cursor Step into Step out
34
F8 F11 F12 CTRL+B CTRL+W Delete BACKSPACE CTRL+BACKSPACE CTRL+DELETE CTRL+SHIFT+DELETE Execute SQL F5 F9 Find and Replace CTRL+F F3 SHIFT+F3 CTRL+G CTRL+I CTRL+SHIFT+I ESC Indent TAB SHIFT+TAB Macros
Step over Run to breakpoint Run to cursor Set breakpoint Add watch at cursor Description Deletes the selected text (if text is selected); otherwise, deletes the previous character Deletes text to the beginning of the previous word Deletes text to the beginning of the next word Deletes the entire line Description Executes the SQL script Executes the SQL statement Description Finds text Finds the next occurrence of text Finds the previous occurrence of text Go to line number Performs an incremental search Performs a reverse incremental search Exits the incremental search mode Description Indents the selected line Outdents the selected line Description
35
CTRL+SHIFT+R CTRL+SHIFT+P Miscellaneous F4 F6 CTRL+D SHIFT+F8 CTRL+ CTRL+ <auto-replace token>+SPACE CTRL+SPACE <code snippet shortcut name>+CTRL+SPACE CTRL+DELETE
Start/Stop recording a macro Play the recorded macro Description Describes the object next to the cursor Toggles between the Editor and Data Grid Send SQL to Query Builder Recalls the previous SQL statement Scrolls up the window. Scrolls down the window Automatically replaces a misspelled word, inserts symbols, and expands text Displays the Code Snippets folder browser Inserts the code snippet template Sets the column value for the current cell to Null in the data grid
Troubleshoot Data
l
If you cannot edit data, click the red icon in the lower left corner of the grid, and then click OK on the window that displays. You do not need to edit fields in this window. By default, auto commit is enabled and any row changes you make are automatically submitted to the database. You can disable this option in Tools |Options | Environment | Grid.
36
Right-click below the column you want to apply the summary function (but above the Navigation toolbar) and select an option. Right-click the column and select Show | Existing Values.
37
If you want to synchronize data, use Data Compare instead of the Data Diff Viewer. You cannot modify files in the Diff Viewer at this time.
To compare differences 1. Right-click data in the Editor's result set or Database Explorer's Data tab and select Compare To | Set_number. You can also save a result set and later use it as a historical comparison. 2. Use the Diff Viewer toolbar to view any differences. Tips:
l
To switch the contents of the left pane to the right pane, and the contents of the right pane to the left, click . beside the drop-down list at You can also open files to compare by clicking the top of each pane.
Before you can export to Excel, the Primary Interop Assemblies (PIAs) for your version of Excel must be installed. Use the Export wizard if you need to specify column delimiters and advanced field options when exporting data.
38
To export data in one click 1. Select the range of data to export or click any row to export all data. Note: If you select a One Click Export option and a window containing data does not have focus, the following message displays: "Export did not find any results sets to process". 2. Review the following for additional information: Icon Option Excel File Description Select this option to export data to an Excel file. The file is automatically saved under a default name in the default export folder. Select this option to export data to a CSV file (comma separated value file). The file is automatically saved under a default name in the default export folder. Select this option to export data to an HTML file. The file is automatically saved under a default name in the default export folder. Select this option to export data to an Excel instance. Data is copied to a clipboard, Excel is launched, and a worksheet is populated with data. You can save the worksheet under a name and folder you specify or in the default export folder. Select this option to export data to an active cell in Excel. First open Excel and select a cell. Then select the Excel Instance at active cell option.
CSV File
HTML File
Excel Instance
39
Icon
Option Excel Pivot Table Excel Pivot Table at active cell Excel Linked Query Excel Linked Query at active cell Excel Linked Query with pivot table Excel Linked Query at active cell with pivot table
Description Select this option to export data to an Excel pivot grid report. See the Excel documentation for information on creating a Pivot Table report with external data. Select this option to export data to an active cell for an Excel Pivot Table report. First open Excel and select a cell. Then select the Excel Pivot Table at active cell option. Select this option to export the underlying query for data to Excel. Select this option to export the underlying query for data to an active cell in Excel. First open Excel and select a cell. Then select the Excel Linked Query at active cell option. Select this option to export the underlying query for data to an Excel Pivot Table report. See the Excel documentation for information on creating a pivot grid report with external data. Select this option to export the underlying query for data to an active cell for an Excel Pivot Table report. First open Excel and select a cell. Then select the Excel Linked Query at active cell with pivot table option.
Tip: To refresh data in a linked query report, click in Excel's External Data toolbar. This executes the underlying query for the report. See "Share Excel Linked Queries" (page 39) for more information about creating and using linked queries. Tip: You can specify a default export folder in Tools | Options |Environment |One Click Export.
40
Notes:
l
Any user who opens an Excel linked query must have access to a user name and password for the queried database to refresh the data. If a user does not have access to the database, they can only see the original data in the spreadsheet. If the Excel linked query was created from an ODBC connection that uses a Data Source Name (DSN), the DSN must also exist on the computer where the Excel file is opened to refresh the data.
Scenario
You need to create an Excel linked query so that the Regional Sales Manager, can track whether the Sales Representatives in his region meet their monthly and quarterly goals. By providing a linked query, you only have to create the query once, and then the Regional Sales Manager can refresh the data at any time to view the latest sales information. To create an Excel linked query 1. Connect to the database. 2. Create a query in the Query Builder or Editor. 3. Execute the query to display data results. 4. Select the result set and click one of the following options from the toolbar:
5. Save the Excel spreadsheet. 6. Email or upload the spreadsheet to a shared network folder to share it with colleagues. To refresh data in an Excel linked query 1. Open the spreadsheet with the linked query in Excel. The original data from the query displays. 2. In Excel, select Data | Refresh to update the original data with the current data. 3. If prompted, enter a user name and password to connect to the database and refresh the data. or
41
If the following error displays: "[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified", you must specify the DSN used by the query on your computer. Complete the following steps to resolve this issue: (Excel 2003) a. Click OK. b. Select the Machine Data Source tab, and then click New. c. Use the wizard to select a User Data Source and create a DSN that points to the database. d. Click OK to return to Excel and open an ODBC Driver Connect window. e. Enter a user name and password to refresh the data.
5
Report
Scenario:Create a Toad Data Report
Use the Data Report Designer to design reports visually. Stored in .tdr files, data reports are "live" reports that can be refreshed dynamically. What makes them dynamic is that they contain the underlying queries for report data sets. Each time a data report is opened, its query runs and the latest data is retrieved. The dynamic nature of data reports makes them ideal for distribution to users who need to see changes to data without waiting for scheduled updates or for new reports to be distributed. The process of creating a data report has the following steps:
l l l l
Step 1: Run the Toad Data Report Wizard Step 2: Update Fields Step 3: Use Styles to Format the Report Appearance Step 4: Update Bands and Add Controls
Note: This procedure does not cover all of the possible steps of creating a data report. It only covers the steps required to create a report for the scenario.
Scenario
Your company wants to improve its global sales, starting with countries where it has a customer base but averages low sales. You created a query that displays countries with less than $500,000 in sales per fiscal year, but now you need to create a report to help represent and evaluate the results. The data should be grouped per country and show the total and average sales for each country. In addition, you want the report to look similar to the rest of the company's documents, which use specific colors and fonts. Note: This scenario uses the data generated in Visually Build a Query.
43
4. Select COUNTRY_NAME and click , and then click Next. This groups the data by the country name so that each country is listed as a heading and its sales per year display below it. Tip: You can create a secondary group by selecting another column and clicking again. A secondary group is not appropriate for this scenario, but it would be if the data included regions in each country or fiscal quarters. You would need to make the region or fiscal quarter a secondary group for the data to be organized appropriately. 5. Select the Sumand Avg checkboxes for the SUM(SALES.AMOUNT) row, and then click Next. These options calculate the sum and average sales amount for each country. 6. Select Outline 1 and click Next. Tip: The Outline and Align Left options are good choices if you grouped the data. 7. Select Casual and click Next. 8. Enter Countries with Sales Less Than $500,000 in the Report Title field, and then click Finish. The initial report layout displays in the Report window with the information grouped under bands. For more information on bands, see Add Report Bands in the Toad help. 9. Click Preview to see what the report looks like in print. Previewing the report makes it easier to see how the bands and their content display in the printable report.
c. Click
d. Clear the Prefix field and click OK. 2. Double-click the following fields and enter their new name: Field FISCAL YEAR SUM(SALES.AMOUNT_SOLD) Band groupHeaderBand2 groupHeaderBand2 Name Fiscal Year Sales Amount
44
Field Avg
Band groupFooterBand1
Name Average
3. Select the following fields one at a time and make them wide enough to see the full text: Sum (groupFooterBand1), Average (groupFooterBand1), and Grand Total (reportFooterBand1). 4. Select the following fields one at a time and drag them to the one inch mark on the ruler: Sum, Average, and Grand Total. 5. Right-click the COUNTRY NAME field (not the COUNTRY_NAME field on the right) in groupHeaderBand1 and select Delete. Note: The COUNTRY NAME field is a label that precedes the COUNTRY_NAME field value. If you preview the report before you delete the COUNTRY NAME field, the country displays as 'COUNTRY NAME Argentina'. It is clear that Argentina is the country name, so this field is redundant. 6. Select the COUNTRY_NAME field and drag it to align with the report title. 7. Select the COUNTRY_NAME field and make it three inches wide to accommodate long country names.
f. Select 22 in the Size field and click OK. 2. Complete the following steps in the Styles Editor window to create and define four new styles: a. Click four times in the Styles Editor window to create four new styles.
45
First Style Name Background Color Border Color Borders Font Second Style Name Border Color Borders Font Third Style Name Background Color Font Foreground Color Fourth Style Name Font Foreground Color
Properties OddRow WhiteSmoke MidnightBlue Bottom Tahoma, 10pt Properies EvenRow MidnightBlue Bottom Tahoma, 10pt Properies TableHeading MidnightBlue Tahoma, 10pt, bold White Properies CountryName Tahoma, 14pt, bold Black
3. Complete the following steps to apply the new styles: a. Expand the Styles field in the Properties pane. b. Select TableHeading in the Style field (under Styles) for the Fiscal Year and Sales Amount fields in groupHeaderBand2.
46
c. Set the following fields for [FISCAL_YEAR] and [SUM(SALES.AMOUNT_ SOLD)] in detailBand1: Field Even Style Odd Style Property EvenRow OddRow
d. Select the COUNTRY_NAME field in groupHeaderBand1 and then select CountryName in the Style field.
47
4. Click Preview. The print preview displays with the following layout:
5. To save the report, right-click the Data Report Designer tab and select Save File.
48
Manage Reports
About Managing Reports
Use the Report Manager to create and organize data reports, add existing Toad or Excel reports, or generate reports. To create a report 1. Select Tools | Reports | Report Manager from the menu. 2. Right-click a folder and select Create Report. 3. Complete the wizard and design the report. 4. Save the report. 5. To add the report to the Reports Manager window: a. Navigate to the open Reports Manager window. b. Right-click the folder where you want to add the report, and select Add Existing Report. To generate an existing report 1. Select Tools | Reports | Report Manager from the menu. 2. Double-click the existing report. 3. Review the following for additional information: Direction Value Select the direction of variable from the list. Enter the value of the variable. Note: Enter a percent (%) in this field to generate all values. Tips:
l
To add an existing Toad or Excel report to the Report Manager, right-click the Report Manager window and select Add Existing Report. To send a Toad or Excel report via email or to a shared folder or other location, rightclick the report, select Send To, and then select an option. To share reports with other users, specify a shared network directory in Network Share Options (Tools | Options |Environment |Network Share).
49
DB2 Reports
The following reports are available from the Reports Manager (Tools |Reports | Reports Manager). Report Name Activity Description Lists and describes activity reports that the Activity Monitor for the current DB2 for LUW database uses. This report also lists the switches required to gather data for a specific activity report. Toad uses the AM_BASE_RPTS table function to generate this report. Displays information from the database history table for the DB2 for LUW database partition to which Toad is currently connected. Toad uses the ADMIN_LIST_HIST table function to generate this report. Shows information about each database partition on the current DB2 for LUW database. Toad uses the DB_PARTITIONS function to gather this information from db2nodes.cfg. Lists the database manager configuration parameters and their values defined for the current DB2 for LUW database. Shows the current "health" status of all containers that tablespaces in the current DB2 for LUW database use. Toad uses the HEALTH_CONT_HI table function to generate this report. Shows a "health" history for all containers that the tablespaces in the current DB2 for LUW database use. Toad uses the HEALTH_ CONT_HI_HIS table function to generate this report. Identifies the containers that tablespaces in the current DB2 for LUW database use and lists the highest current alert status for each container. Toad uses the HEALTH_CONT_INFO table function to generate this report. Shows the "health" status of the current DB2 for LUW database, including its highest current alert status. Toad uses the HEALTH_ DB_HI table function to generate this report. Shows the "health" history of the current DB2 for LUW database. Toad uses the HEALTH_DB_HI_HIS table function to generate this report. Shows the "health" status of objects in the current DB2 for LUW database. Toad uses the HEALTH_DB_HIC table function to generate this report.s Displays a "health" history for objects in the current DB2 for LUW
ADMIN_LIST_ HIST_V82
Database Partitions DBManager Config Info HEALTH_ CONT_HI HEALTH_ CONT_HI_HIS HEALTH_ CONT_INFO
HEALTH_DB_HI
50
Report Name
Description database. Toad uses the HEALTH_DB_HIC_HIS table function to generate this report.
HEALTH_DB_ INFO HEALTH_DBM_ HI HEALTH_DBM_ HI_HIS HEALTH_DBM_ INFO HEALTH_TBS_ HI HEALTH_TBS_ HI_HIS HEALTH_TBS_ INFO Index Statistics
Shows the highest current alert status for the current DB2 for LUW database. Toad uses the HEALTH_DB_INFO table function to generate this report. Shows the "health" status for the current DB2 for LUW instance. Toad uses the HEALTH_DBM_HI table function to generate this report. Shows a "health" history at the database manager level for the current DB2 for LUW instance. Toad uses the HEALTH_DBM_ HI_HIS table function to generate this report. Shows the highest current alert status for the current DB2 for LUW instance. Toad uses the HEALTH_DBM_INFO table function to generate this report. Shows the "health" status of all tablespaces in the current DB2 for LUW database. Toad uses the HEALTH_TBS_HI table function to generate this report. Shows a "health" history for tablespace in the current DB2 for LUW database. Toad uses the HEALTH_TBS_HI_HIS table function to generate this report. Shows the highest current alert status for each tablespace in the current DB2 for LUW database. Toad uses the HEALTH_TBS_ INFO table function to generate this report. Displays statistics for the indexes under the current schema for the DB2 for LUW database and flags those indexes that need reorganization. Toad uses the REORGCHK_IX_STATS procedure to generate this report. Lists the DB2 for LUW 9 products currently installed on your system. Toad uses the ENV_GET_PROD_INFO table function to generate this report. Products can include the following: RTCL DB2 Run-Time Client CONSV DB2 Connect Server (any edition) CONPE DB2 Connect Personal Edition
51
Description Lists the DB2 for LUW 8 products currently installed on your system. Toad uses the ENV_GET_PROD_INFO table function to generate this report. Products can include the following:
l l l
ADCL DB2Application Development Client ADMCL DB2Administration Client CONEE DB2Connect Enterprise Edition, DB2 Connect Unlimited Edition, or DB2 Connect Application Server Edition CONPE DB2Connect Personal Edition CUBE DB2Cube Views DLM DB2Data Links Manager ESE DB2Enterprise Server Edition EXP DB2Express Edition or DB2 Express Edition processor option GSE DB2Spatial extender PE DB2Personal Edition QP DB2Query patroller RTCL DB2Run time client WM DB2Warehouse Manager WSUE DB2Workgroup Server Unlimited Edition
l l l l l
l l l l l l
Lists details about the current DB2 for LUW instance. Toad uses the ENV_GET_INST_INFO table function to generate this report. Provides recommendations (in English) for the various activity reports that the activity monitor uses. Toad uses the AM_BASE_ RPT_RECOMS table function to generate this report. Displays information and statistics about each container that tablespaces in the current DB2 for LUW 8 database use. To generate this report, Toad uses the SNAP_GET_CONTAINER table function to retrieve information from the tablespace_ container logical data group. Lists information and statistics captured for the current DB2 for LUW 8 database. To generate this report, Toad uses the SNAP_ GET_DB table function to retrieve information from the database and detail_log logical data groups.
SNAP_GET_DB_ V82
52
Description Lists statistics and information about the dynamic SQL statements executed against the current DB2 for LUW 8 database use. To generate this report, Toad uses the SNAP_GET_DYN_SQL table function to retrieve information from the dynsql logical data group. Lists information and statistics about the tables in the current DB2 for LUW database 8. To generate the report, Toad uses the SNAP_ GET_TAB table function to retrieve information from the table logical data group. Lists information and statistics for the database partitions that make up each tablespace in the current DB2 for LUW 8 database. To generate this report, use the SNAP_GET_TBSP_PART table function to retrieve information from the tablespace_nodeinfo logical data group. Lists information and statistics for each tablespace in the current DB2 for LUW 8 database. To generate the report, Toad uses the SNAP_GET_TBSP table function to retrieve information from the tablespace logical data group. Lists the agents working for the various applications connected to the current DB2 for LUW 8 database. To generate the report, Toad uses the SNAPSHOT_AGENT function to retrieve information from the application snapshot, especially from the agent logical group. Displays information about the operating system in which the current DB2 for LUW 8 database operates and about the CPUs configured on this operating system. Toad uses the ENV_GET_ SYS_INFO table function to generate this report. Displays statistics for the tables under the current schema in the DB2 for LUW database and flags those tables that need reorganization. Toad uses the REORGCHK_TB_STATS procedure to generate this report. Displays statistics for the tables under the current schema in the DB2 for LUW database and flags those tables that need reorganization. Toad uses the REORGCHK_TB_STATS procedure to generate this report.
SNAP_GET_ TAB_V82
SNAP_GET_ TBSP_V82
SNAPSHOT_ AGENT_V82
System Information_V82
Table Statistics
MySQL Reports
The following reports are available from the Reports Manager (Tools |Reports | Reports Manager).
53
ODBC Reports
The following reports are available for the Toad Sample Database in the Reports Manager (Tools |Reports |Reports Manager): Report Name Customer orders Customer list Items to order Description Displays customer orders for contact IDs less than 10 from the Toad sample database. It is an example of master detail display using a single result set. Displays a list of customers from the Toad sample database. Displays items in stock that have a quantity of less than 50 and should be reordered from the Toad sample database.
Oracle Reports
The following reports are available from the Reports Manager (Tools |Reports | Reports Manager). Cluster Reports Report Name Clusters Description Displays cluster information, including the cluster type, definitions, storage parameters, and affected tables.
Other Reports Report Name Invalid objects Loads into shared pool Description Displays any invalid objects for the selected schema and includes a subtotal of all invalid objects for that owner. Displays packages that have been loaded five or more times, into the Oracle shared pool. Note: You must have DBA privileges for this report. Non-system objects in SYSTEM tables Displays any objects in the SYSTEM tablespace that are not owned by SYSTEM.
54
Report Name Oracle initialization parameters Tablespaces near capacity Total shared pool reload stats User hit ratios User resource usage Sequence reports Report Name Sequences
Description Displays the values for all parameters defined in the PFILE for the selected user. Displays tablespaces that over 90% full, and do not have the autoextend feature enabled. Displays the number of times objects in the shared pool were reloaded. Note: You must have DBA privileges for this report. Displays the buffer cache hit ratio users and includes consistent gets, blocked gets, and physical reads. Displays values for resource usage such as CPU used and SQL*Net roundtrips for each user.
Description Displays the sequences that are within 10% of the maximum value. Any sequences that do not have a maximum value set, or those that cycle are excluded from the report. Displays the sequences that are within 10% of the maximum value. Any sequences that do not have a maximum value set, or those that cycle are excluded from the report.
Stored Program Reports Report Name Arguments of stand-alone stored programs Object type bodies Object types Package bodies Package Description Displays any parameters required for the selected stored procedure.
Displays the body or source code for a selected object. Displays the type of objects owned by a user, including whether the objects are valid and when they were created or last modified. Displays the body or source code for a selected package Displays specifications for a selected package, including whether it is
55
Report Name specifications Stand-alone stored programs Stored functions Stored object with source Stored procedures Synonym Reports Report Name Synonyms
Description valid and when it was created or last modified. Displays the source code for a stored program, including the type of program and the last time DDLwas generated. Displays a list of stored functions for a selected owner. Displays a list of all stored programs including their source. Displays the source for stored procedures for a selected owner.
Description Displays information for each synonym, including the owner, table owner and name, and the DB link.
Table Reports Report Name Indexes Non-indexed tables Table comments Tables & columns Tables & indexes Trigger Reports Report Name Triggers & columns Description Displays triggers for a selected table, including the trigger event, status, WHEN clause, and columns associated with the trigger. Description Displays details for the index definition, storage parameters, and columns included in the index. Displays any tables that have not been indexed for the selected database. Displays any comments for the selected table. Displays all columns for a selected table, including the maximum transactions, used/free blocks, free lists and groups, min/max extents, and columns included in this index. Displays any indexes for a selected table, including the status, uniqueness, and columns included in the index.
56
User-defined Reports Report Name Sample View Reports Report Name View comments Views & columns Description Displays any comments for the selected view. Displays all columns for a selected view, including the query and columns included in the view. Description Displays a sample user report based on a select * from dual query.
57
Description Displays space for all databases on the server, including free space, space used, maximum size, and growth type. Displays tables in the order you can either populate or delete from them without violating any foreign key constraints. Objects with the lowest wave number indicate that they can be deleted with the fewest number of foreign key references. Objects with the highest wave number should be populated first. (SQLServer 2000 only) Displays all indexes for the current database sorted by table. Index information includes whether it is clustered, unique, index keys, and the index size. run frequency, and the maximum duration. (SQLServer 2000 only) Displays all SQLServer jobs, including whether they are scheduled, enabled, start date and time, Displays the number of rows for all tables on a server that contain a clustered index.
Index description
Job details Row count for tables with clustered index Total rows and space used User permissions
Displays the total number of rows and space used for each table or view in the current database, including the reserved rows, unused rows, and index size. This report is sorted in descending order by reserved rows. Displays users permissions, grouped by role name and object type.
Other Reports (SQLServer 2005 only) Report Name Configuration change history Schema change history Table Reports Report Name Indexes Description Displays index information for a selected table, including whether the index is clustered, unique, ignores duplicate keys, allows page/row locks, and a list of indexed columns. Description Displays a history of all sp_configure and Trace Flag Changes recorded by the default trace. Displays a history of all committed DDL statement executions recorded by the default trace.
58
Description Displays any tables that have not been indexed for the selected database. Displays any check constraints for a selected table, including whether the constraint is enabled, valid data, and affected columns. Displays any extended properties for a selected table. Displays any foreign key constraints for a selected table, including whether the constraint is enabled, referenced tables, and referenced keys. Displays all columns for a selected table, including the data type, default value, whether it allows null values, and for SQLServer 2005 any extended properties. Displays any indexes for a selected table, including the name, columns included in the index, and whether it is unique or clustered.
User-defined Reports Report Name Stored procedures Description Displays stored procedures for a selected database, including their status, status, replication information, schema version, statistics, and procedure text.
Email reports and files, including ER diagrams, Query Builder queries, SQL scripts, and results for reports, queries, and scripts. Share reports and files in a central location such as the Toad shared folder. Add reports and files to a ZIP folder or file. Publish reports and files to a web site.
You can use the following methods to publish and share information:
59
Do this... Right-click a report or file and select Send To | Mail Recipient. Drag the Send Email activity to the Automation workflow and attach files as needed. The email is sent when the automation script executes. Do this... Right-click a report or file and select Send To | Toad Shared. The file is sent to the Toad shared folder specified in Tools |Options |Environment |Network Share. Drag the Copy File activity to the automation workflow. Specify the file to copy or move and a destination folder. This can be any folder, including the Toad shared folder, or a network folder. The file is copied or moved when the automation script executes. Do this... Right-click a report or file and select Send To | Compressed (zipped) Folder. Note: This function requires that ZIP files be associated with the Compressed (zipped) Folders feature instead of WinZip or another ZIP file handler.
Automation
Drag the Zip File activity to the workflow. Add reports and files to the Zip file and specify a file name with a .zip extension. The ZIP file can then be emailed with the Send Email activity or copied with the Copy File activity. Do this... Right-click a report or file and select Send To | Web Publishing Wizard. Complete the wizard to specify a URL and directory for the file.
Tips:
l
To export a Toad report to a file that can be read by other applications, double-click a report in the Reports Manager, click in the Report Preview window, select a file format, and add the file to a project. Share or publish the file using the Project
60
Manager functions.
l
To capture report results in a file, add the Toad Report automation activity. This activity runs a Toad report and saves the results in a file format you select. Share or publish the file using the Automation functions. To execute and save a query in a file, add the Select To File automation activity. This activity runs a query or SQL script and exports the results to an Excel spreadsheet. Share or publish the spreadsheet using the Automation functions.
6
Automate
Scenario: Automate a Query and Email the Report
Scenario
You need to create an Excel report that contains current regions and addresses and email it to your manager every week. Note:This scenario uses the Toad Sample(Access) database that ships with Toad for Data Analysts. To automate a task for this scenario 1. Connect to the Toad Sample (Access) database in the Navigation Manager. 2. Enter the following statements in the Editor and save them to a single file named AutomationTest.sql:
Select * from region; Select * from address;
3. Select Tools | Automation from the menu. 4. To send yourself an email if an error occurs, double click Script Settings to open the Activity Editor window and enter the following: Error Email on Error Error Email To From Error Email Server Server Port Description Select True. Description Enter your email address. Enter your email address. Description Enter your SMTP server address. Update the port number, if needed.
5. Click the Select To File database activity in the toolbox to add it to the design pane. 6. Double-click the Connection_1 activity in the design pane and select Toad Sample
62
Database in the Connection field. Note:All activities that need a database connection must be a child activity of that connection. 7. Double-click the File_1 activity and enter the following in the Activity Editor window: Export SQL Script Export Options Description Select AutomationTest.sql. Select the following options:
l
DestinationEnsure that the Excel file option is selected. Then, select a folder and enter AutomationTestExcel as the file name. Add Date/Time suffix to filenameSelect this checkbox.
8. Click the Send Email file activity in the toolbox to add it to the design pane. 9. Double-click the Send Email activity and enter the following in the Activity Editor window: Email Server Server Port Message To From Attachments Description Enter your SMTP server address. Update the port number, if needed. Description Enter your email address. Enter your email address. Click the arrow to open Attachment Editor window. Select AutomationTestExcel from Activity Reports and click Add. Click the X in the upper-right corner of the dialog. The file is added as an email attachment. Subject Body Enter Weekly Report. Enter the following: Attached is a copy of the weekly regions and addresses report.
10. Save the Automation script. 11. Click Test on the wizard bar to ensure that the script works. The automation script is compiled, then executed. All results display in the Output window.
63
12. Review the outputand Click the Excel file generated to open the Excel file in Toad. Notice that the results of each SQL statement are in a different worksheet. 13. To schedule the automation script to run at a later time, click Schedule on the wizard bar. 14. Complete the following fields: Task Tab Set password Schedule Schedule task Start time Description Click this button and enter and confirm your O/S password. Description Select Once. Select a time that is 2 minutes from the current time.
15. Check your email for confirmation of execution as well as thestatus of the job manager window.
Automate Tasks
Use Automation to schedule a single script to run reports and queries, save results in Excel spreadsheets, and distribute results to the business community via email. You can schedule scripts that perform long-running tasks to run when database activity is light. You can also use variables in automation scripts. With variables, you can update information that may be different each time you run the script, such as the department name, revenue, fiscal quarter, or product name. See "Use Variables in Automation" (page 75) for more information. For example, assume you are an analyst at Nick's Flicks movie rentals. You need to run inventory and movie rental reports on a daily basis and distribute them to managers of the inventory department. Using Toad, you create an automation script that runs the reports, exports them to Excel spreadsheets, and emails the spreadsheets to the inventory department everyday at 2:00 AM. Troubleshooting: If Toad displays a "Variable must be initialized before referencing itself" error, you need to initialize the variable. See "Use System Automation Activities" (page 71) for more information. Note: This topic focuses on information that may be unfamiliar to you. It does not include all step and field descriptions. To automate tasks 1. Click Automate. 2. Double-click Script Settings in the Design pane to specify exception handling and
64
logging levels. Note: Exception handling uses email to notify you of an error. You must specify email values for the SMTP server, To, and From fields in the Script Settings dialog to receive error notifications. Once you specify the email values, they are retained in the settings and used by all subsequent scripts. 3. Click one or more activities to automatically add them to the Design pane. See the following topics for additional information:
l l l
Use Database Automation Activities (page 65) Use File Automation Activities (page 68) Use System Automation Activities (page 71)
4. Specify properties for each activity in the Activity Properties pane. You can also double-click an activity to specify properties in a window. Tip: If you frequently use the same properties for an activity, you can save the activity as a template by right-clicking and selecting Save As Template. You can then add the pre-populated template to a script. After you create the first template, a Templates toolbox displays. 5. Use the Wizard bar to do the following: Click this... Add to Project Save Test To... Add an automation script to the current project in the Project Manager. The script is automatically placed in the project's Automation Scripts folder. Save an automation script (.tas) in a folder on a local or network drive. Test an automation script before scheduling it. The script executes once and status messages display in the Output window. Resolve any problems that cause activities to fail or disable failed activities before scheduling the script. Tip: Press F5 to test the automation script. Schedule Schedule an automation script in Job Management. A script can be scheduled to execute once or repeatedly at an interval you specify.
65
Row count variableEnter a name for the row count variable, which Toad populates with the number of rows returned from the activity. You can use this variable with the If..Condition.. and While system activities. See "Use Variables in Automation" (page 75) for more information on use cases for this field. SQL ScriptSelect a SQL script or Query Builder query to run. For SQL scripts, you can create a new worksheet for the results of each SELECT statement in a script by entering GO after each statement. File OptionsClick the drop-down list to select the file type. Then, select the file location and enter the name. You can use a variable in this field by entering the number sign before and after the variable (#VariableName#). If you select Excel file, you can append the date and time that the file was generated to the file name as a suffix. Note: You can only use one variable per field or file name (a suffix counts as one variable for a file name).
Execute Script
Execute an existing SQL script or Query Builder query. Review the following for additional information:
l
Row count variableEnter a name for the row count variable, which Toad populates with the number of rows returned from the activity. You can use this variable with the If..Condition.. and While system activities. See "Use Variables in Automation" (page 75) for more information on use cases for this field.
66
Activity
Description
l
SQL ScriptSelect a SQL script or Query Builder query to run. For SQL scripts, you can create a new worksheet for the results of each SELECT statement in a script by entering GO after each statement. Result variableEnter a name for the result variable, which contains a data table with the results of the execution script. You can use the result variable with the Loop Dataset activity. See "Use System Automation Activities" (page 71) for more information.
Execute an existing SQL script or Query Builder query and save it and any results sets in a Toad editor file (.tef). This file format is useful for building scripts that have large result sets that you do not want to continue executing or for saving results when you have not finished building a script. Review the following for additional information:
l
Row count variableEnter a name for the row count variable, which Toad populates with the number of rows returned from the activity. You can use this variable with the If..Condition.. and While system activities. See "Use Variables in Automation" (page 75) for more information on use cases for this field. SQL ScriptSelect a SQL script or Query Builder query to run. For SQL scripts, you can create a new worksheet for the results of each SELECT statement in a script by entering GO after each statement. Editor FileSelect the file location and enter the name. You can use a variable in this field by entering the number sign before and after the variable (#VariableName#). SuffixSelect a suffix to append to the file name. The suffix can be the date and time that the file was generated or the content of a variable that you define with the Set Variable system activity. See "Use System Automation Activities" (page 71) for more information. Note: You can only use one variable per field or file name (a suffix counts as one variable for a file name).
Export Wizard
Export data from databases, tables, views, or query into a CSV, Excel, or other file. You can save the export settings as a template that you can use for scheduled automation scripts. Import data from a CSV, Excel, or other file into a new table or append to an existing table. You can save the import settings as a template that you can use for scheduled automation scripts.
Import Wizard
67
Description Generate a Toad data report and save it to a PDF, RTF, or MHT file. You can then use additional activities to add the report to a zip file, attach the report to an email, or copy the report. Review the following for additional information:
l
Row count variableEnter a name for the row count variable, which Toad populates with the number of rows returned from the activity. You can use this variable with the If..Condition.. and While system activities. See "Use Variables in Automation" (page 75) for more information on use cases for this field. Save Report AsSelect the file location and enter the name. You can use a variable in this field by entering the number sign before and after the variable (#VariableName#). SuffixSelect a suffix to append to the file name. The suffix can be the date and time that the file was generated or the content of a variable that you define with the Set Variable system activity. See "Use System Automation Activities" (page 71) for more information. Note: You can only use one variable per field or file name (a suffix counts as one variable for a file name).
Refresh an existing pivot grid and export results to a report. You can then use additional activities to add the pivot grid to a zip file, attach it to an email, or copy it. Review the following for additional information:
l
Row count variableEnter a name for the row count variable, which Toad populates with the number of rows returned from the activity. You can use this variable with the If..Condition.. and While system activities. See "Use Variables in Automation" (page 75) for more information on use cases for this field. Export ReportSelect the file location and enter the name. You can use a variable in this field by entering the number sign before and after the variable (#VariableName#). SuffixSelect a suffix to append to the file name. The suffix can be the date and time that the file was generated or the content of a variable that you define with the Set Variable system activity. See "Use System Automation Activities" (page 71) for more information. Note: You can only use one variable per field or file name (a suffix counts as one variable for a file name).
Notes:
68
Activity
l
Description
In the Enabled field, select whether to include or exclude the activity in script execution. The False setting allows you to leave the activity in the script until you have time to resolve the problem. In the On Error field, select whether to stop or continue execution if Toad encounters an error. To set activity properties from a window instead of the property grid, doubleclick the activity in the Design pane. Automation does not support positional parameters denoted by a question mark.
Copy NameEnter the name. You can use a variable in this field by entering the number sign before and after the variable (#VariableName#). SuffixSelect a suffix to append to the file name. The suffix can be the date and time that the file was generated or the content of a variable that you define with the Set Variable system activity. See "Use System Automation Activities" (page 71) for more information. MoveSelect True to move a file from the source folder to a destination folder instead of copying it or False to copy the file to the destination folder. If you want to use this activity for files generated by other automation activities, those activities must precede this one. The filenames and paths specified should match the directories and names displayed in properties for the preceding activities. If you frequently use the same properties for an activity, right-click the activity and save the properties as a template. You can then add the pre-populated template to an automation script.
Notes:
l
69
Activity
Description
l
You can only use one variable per field or file name (a suffix counts as one variable for a file name).
Delete one or more files from a specified location. Logs a comment to the Output window. This is useful if you want an on-screen notification that the automation script succeeded or failed. Create a ZIP file and add files to it. Files generated with other activities can be added to the ZIP file. You can then email this file to colleagues. Review the following for additional information:
l
Zip Files
Archive NameSelect the file location and enter the name. You can use a variable in this field by entering the number sign before and after the variable (#VariableName#). EncryptionSelect whether to create a zip file without encryption (Standard) or to encrypt the zip file. Note:If you encrypt the zip file, you must have a zip utility that can support 128-bit or 256-bit decryption.
FilesSelect one or more files. You can select files that are generated by the automation script. If you want to use this activity for files generated by other automation activities, those activities must precede this one. The filenames and paths specified should match the directories and names displayed in properties for the preceding activities. You can only use one variable per field or file name (a suffix counts as one variable for a file name).
Note:
l
Open a file and perform a find and replace within it. You can write the results to a different location and file name. Review the following for additional information:
l
ReplaceEnter the content to replace. You can use a variable in this field by entering the number sign before and after the variable (#VariableName#). In the following example, if variable X has a value of 10, the updated file would display "Region 10" instead of "Region".
70
Activity
Description
l
Copy NameEnter the name. You can use a variable in this field by entering the number sign before and after the variable (#VariableName#). SuffixSelect a suffix to append to the file name. The suffix can be the date and time that the file was generated or the content of a variable that you define with the Set Variable system activity. See "Use System Automation Activities" (page 71) for more information. MoveSelect True to move a file from the source folder to a destination folder instead of copying it or False to copy the file to the destination folder. If you want to use this activity for files generated by other automation activities, those activities must precede this one. The filenames and paths specified should match the directories and names displayed in properties for the preceding activities. You can only use one variable per field or file name (a suffix counts as one variable for a file name).
Notes:
l
Send Email
Send an email to notify yourself or colleagues about the automation script status. The message automatically includes execution status for each activity that precedes the email activity. You can also attach files generated by other activities to the email and include a log file or error messages in the email. Note: To use this activity, an SMTP service must be running. Review the following for additional information:
l l l
ServerEnter the SMTP host. PortEnter the SMTP port number. Typically, this is 25. ToEnter the recipient email addresses. You can use a variable in this field by entering the number sign before and after the variable (#VariableName#). CCEnter the email addresses to carbon copy. You can use a variable in this field by entering the number sign before and after the variable (#VariableName#). AttachmentsSelect one or more files to attach. You can select files that are generated by the automation script. SubjectEnter the subject of the email. You can use a variable in this field by entering the number sign before and after the variable (#VariableName#). BodyEnter the body of the email. You can use a variable
71
Activity
Description in this field by entering the number sign before and after the variable (#VariableName#).
l
Use file for bodySelect a file to use as the body of the email. This is useful if you need to send an email to a mobile device that does not support attachments. For example, you could send the results of an Execute Script activity in the body of the email. You can customize the file with the Find and Replace activity.
Note: You can only use one variable per field or file name (a suffix counts as one variable for a file name). FTP File Notes:
l
In the Enabled field, select whether to include or exclude the activity in script execution. The False setting allows you to leave the activity in the script until you have time to resolve the problem. In the On Error field, select whether to stop or continue execution if Toad encounters an error. To set activity properties from a window instead of the property grid, doubleclick the activity in the Design pane. Automation does not support positional parameters denoted by a question mark.
Return Code VariableEnter a name for the return code variable. You can use this variable with the If..Condition activity. ProgramSelect a .bat or .exe file. ArgumentsEnter command-line arguments. Run DirectorySelect the directory to change to when running the program. VerbEnter verbs used when running the program, such as "Print".
l l l
72
Activity
Description
l
WaitSelect True to wait if there is an error or False if you do not want to wait.
Note: If the script opens a command-line window, you have to manually close the window once the script completes. Set Variable Add a variable to the script. When the script is executed, Toad replaces the variable with the defined value. With this feature you can update information that may be different each time you run the script, such as the department name, revenue, fiscal quarter, or product name. Variables must have an initial numeric value, such as 0 or 1.53. After you initialize the variable, you can add a second Set Variable activity and use a variable expression or another variable as the value. See the Loop dataset activity for an example. See "Use Variables in Automation" (page 75) for more information. Note: You can only use one variable per field or file name (a suffix counts as one variable for a file name). If..Condition Execute activities conditionally based on the value of a variable. For each condition you can define unique activities, such as connecting to a database, generating files, and sending emails. To use this activity you must define a variable in the automation script with the Set Variable activity. This activity can have one or more conditions. To delete a condition, select it and press DELETE. To add a condition, right-click the If..Condition.. activity and select Add Branch. If you have multiple conditions, they do not have to be mutually exclusive. Multiple branches can be true. To define a condition, enter the variable name and expression in the Condition field. You can click the drop-down list to create the expression with an expression builder that uses VBScript functions or to test the expression. See the following link for more information on VBScript functions: http://www.w3schools.com/VBscript/vbscript_ref_ functions.asp While.. Execute activities while the variable condition is true. The activity ends when the condition becomes false, or when it completes the selected number of loops. To use this activity you must define a variable in the automation script with the Set Variable activity. This activity can have one or more conditions. To delete a condition, select it and press DELETE. To add a condition, right-click the If..Condition.. activity and select Add Branch. If you have multiple conditions, they do not have to be mutually exclusive. Multiple branches can be true. Review the following for additional information:
73
Activity
Description
l
ConditionEnter the variable name and expression. You can click the drop-down list to create the expression with an expression builder that uses VBScript functions or to test the expression. See the following link for more information on VBScript functions: http://www.w3schools.com/VBscript/vbscript_ref_functions.asp LoopEnter the number of times to loop the activity. If the condition never becomes false, Toad ends the activity after this number. The default is 10.
Loop dataset
Execute activities on each row of a data table. The data table must be the result set from an Execute Script activity that occurs previously in the automation script. See "Use Database Automation Activities" (page 65) for more information. You can reference a column in the data table by setting the value of an initialized variable to 'DataTableName.ColumnName'. To initialize a variable, your script must have two different Set Variable activities. The first Set Variable activity defines the variable value with a numeric value (such as 0 or 1.53), and the second defines it with the column variable name. For example, assume you want to perform a set of activities on each of your company's products. You add the following activities and values:
l
Execute ScriptExecute a script that returns product IDs. You enter ProductIDTable in the Result variable field. Set VariableAdd activity to give the variable an initial value. You enter ID in the Name field and 0 in the Value field. Loop datasetLoop based on the dataset from the Execute Script activity. You enter ProductIDTable in the Data Table field. Set VariableAdd a second variable activity to reference the Product_ID column in the data table. You enter ID in the Name field and ProductIDTable.Product_ID in the Value field. This redefines the values of the ID variable to the values in the Product_ID column.
74
Activity
Description
See "Use Variables in Automation" (page 75) for more information on a scenario that uses this activity. Parallel Run two or more activities in parallel. After adding a parallel activity to the design pane, you can right-click it to add additional branches for parallel activities. Note: To add an activity that requires a database connection, you must first add the Database Connection activity, and then add the activity for that connection. Attempting to add the activity alone results in a "Designer failed to deserialize the data..." error. Notes:
l
In the Enabled field, select whether to include or exclude the activity in script execution. The False setting allows you to leave the activity in the script until you have time to resolve the problem. In the On Error field, select whether to stop or continue execution if Toad encounters an error. To set activity properties from a window instead of the property grid, doubleclick the activity in the Design pane. Automation does not support positional parameters denoted by a question mark.
75
Send an email to a group of people where the list of recipients is automatically selected with a query Generate repetitive reports where only the product number, date, region, or any other single element changes Customize file names by including a variable in the file name or automatically including the date that the automation script ran Find content in a file and replace it with the value of a variable
Report on warehouse inventoryquery warehouse inventory with the inventory number as the variable, and then use the If..Condition.. activity to create different reports for items with no inventory, low inventory, and high inventory Report on revenue for each fiscal quartercreate a query with the fiscal quarter as the variable Report on revenue per sales personcreate a query with the sales person's name or identification as the variable
Scenario
Your Sales Manager wants a separate sales report for each of the company's products every week. He wants you to email the reports to him once they are generated. To provide the reports to the Sales Manager, you need to create the product queries and the sales report. Then, you can use them in an automation script to run the queries, generate reports, and email the Sales Manager every week. To generate reports per product 1. Use the Query Builder to create a query that returns the product IDs. 2. Save the query and name it ProductIDQuery.tsm. 3. Use the Query Builder to create a query that returns the sales information for products and enter the following search criteria in the specified columns:
76
Column Product_ID
Search Criteria Click in the Where Condition field. Select = and then Constant. Enter :ID in the field to define the variable. Click in the Where Condition field. Select the Date Range tab and then Last week.
Order_Date
4. Save the query and name it ProductSalesQuery.tsm. 5. Click Run Query and enter a value for the ID variable. The query results display. 6. Right-click the query results and select Send To | Data Report Designer. 7. Create the data report. 8. Save the report and name it ProductSalesPerWeek.tdr. 9. Close the report. 10. Click Automate to create a new automation script. 11. Click the Execute Script activity to add it to the Design pane and complete the following fields: SQLScript Result variable Select ProductIDQuery.tsm. Enter ProductIDTable.
12. Click the Set Variable activity and complete the following fields: Name Result variable Enter ID. Enter 0. Entering a number initializes the variable, which is required before you can redefine the value to another variable.
13. Click the Loop dataset activity and enter ProductIDTable in the Data Table field. This loops activities on the content of the ProductIDQuery.tsm query. 14. Click the Set Variable activity to add a second variable and drag it into the Loop row. 15. Complete the following fields for the new Set Variable activity: Name Result variable Enter ID. Enter ProductIDTable.Product_ID. This uses the content of the Product_ID column in the ProductIDTable table as the values for the variable.
16. Click the Database Connection activity and drag it into the Loop row beneath the Set Variable activity. 17. Click the Toad Report activity and drag it into the new Database Connection activity. 18. Complete the following fields in the Toad Report activity:
77
Select ProductSalesPerWeek.tdr. Select the file location and enter SalesForProduct#ID# for the file name. When the automation script runs, it replaces #ID# with the variable value. Note: You can only use one variable per field or file name (a suffix counts as one variable for a file name).
19. Click the Send Email activity and drag it beneath the Database Connection activity in the Loop row. 20. Enter the following information and then complete the remaining required fields for the Send Email activity: To Attachments Subject Enter the Sales Manager's email address. Select the file created in the Toad Report activity and click Add. Enter Weekly sales report for product #ID#. When the automation script runs, it replaces #ID# with the variable value. Enter the following: Attached is the weekly sales report for product #ID#. See the attached file.
Body
21. Click Test to ensure that the script works. The following image displays the automation script in the Design pane:
78
If ProductIDQuery.tsm returns five product IDs, Toad creates a report and sends an email for each one. If the first product ID is 101, the first email would have the following properties: Attachments Subject Body SalesForProduct101.xls Weekly sales report for product 101 Attached is the weekly sales report for product 101. See the attached file.
79
23. Schedule the automation script to run weekly. See "Execute Automation Scripts" (page 82) for more information.
Find Unbatched Transactions (Use the Row Count Field and If..Condition.. Activity) Scenario
Your company has a web site that customers use to order products. The orders are automatically batched, and each order is recorded as a row of data. When the batch is sent, it updates a column in the order row. You need to run a daily report to find orders that were submitted but not batched. If there are any unbatched orders, you need to send an email to yourself with a list of the unbatched orders. If there are no unbatched orders, you need to send an email to yourself so you know that all orders were batched successfully. To generate a daily report of unbatched orders 1. Save the query and name it UnbatchedOrders.tsm. 2. Click Automate to create a new automation script. 3. Click the Execute Script activity to add it to the Design pane and complete the following fields: Row count variable SQLScript Enter rc. Select UnbatchedOrders.tsm.
4. Click the If..Condition.. activity. 5. Complete the following steps to define the first condition: a. Select the first condition and enter rc=0 in the Condition field. b. Click the Send Email activity and drag it into the first condition. c. Complete the required Send Email activity fields and enter No unbatched orders in the Subject field. 6. Complete the following steps to define the second condition: a. Select the second condition and enter rc>0 in the Condition field. b. Click the Database Connection activity and drag it into the second condition. c. Click the Select to File activity and drag it into the Database Connection activity in the second condition.
80
d. Complete the following Select to File activity fields: SQLScript File Options Select UnbatchedOrders.tsm. Click the drop-down and complete the following:
l
Excel fileSelect this option, and then select the file location and enter UnbatchedOrders_ for the file name. Use column names for header rowSelect this option and select a header row color. Add Date/Time suffix to filenameSelect this option and then select Date in the drop-down. This option appends the date the automation script ran to the file name.
e. Click the Send Email activity and drag it beneath the Select to File activity. f. Enter the following information and then complete the remaining required fields for the Send Email activity: Attachments Subject Select the file created in the Select to File activity and click Add. Enter #rc# unbatched order(s). When the automation script runs, it replaces #rc# with the variable value. Enter the following: There were #rc# unbatched orders. See the attached file for more information.
Body
7. Click Test to ensure that the script works. The following image displays the automation script in the Design pane:
81
If there are no unbatched orders, Toad executes the first condition and sends an email with "No unbatched orders" in the subject . If there are unbatched orders, Toad executes the second condition. If there are two unbatched orders and you test on December 10, 2009, the email would have the following properties: Attachments Subject Body UnbatchedOrders_2009-12-10.xls 2 unbatched orders There were 2 unbatched orders. See the attached file for more information.
8. Save the automation script. 9. Schedule the automation script to run daily. See "Execute Automation Scripts" (page 82) for more information.
82
See our web site for regional and international office information.
Index
A activities, Automation Automation automate query and email report tutorial database activities execute automation scripts file activities system activities variables B build queries create heterogenous queries reverse engineer queries C code shortcut keys view result sets connections create ODBC share for all session windows understand contact support 7 9 8 83 32 35 23 25 63 63 61 65 82 68 71 75
D data browse parent tables compare differences export in one click in result sets reports tutorial Database Explorer best method for locating objects filter databases and objects search for objects database objects filter schemas object explorer search for databases automation activities Diff Viewer, data E Editor reverse engineer queries shortcut keys ER Diagrams tutorial Excel add to Report Manager share linked queries 48 39 17 31 25 32 65 37 10 11 16 10 11 10 16 19 37 37 35 42
85
export data with one click F files automation activities filter databases and objects H heterogeneous queries I intellisense shortcut keys K keyboard shortcuts L linked queries M Master Detail Browser O Object Explorer filter databases and objects search for objects object search ODBC create connections One Click Export 7 37 10 11 16 16 script results search database objects shortcut keys SQL shortcut keys 19 39 32 32 23 reports data tutorial DB2 manage reports MySQL ODBC Oracle publish and share SQLServer result sets 11 68 Query Builder 37 parameters in Automation
75 Q
23 25 21
48 42 49 48 52 53 53 58 56 35 25
35 16 16 32
32
86
SQL Editor system automation activities T tables browse data in related tutorials
31 71
19 42
automate queries and email reports 61 create ER diagrams create ODBC connections create Toad data reports visually build queries V variables in Automation 75 17 7 42 21