running db2 queries

39
Running DB2 Queries – Part 1 30 October 2010 Updated 2 January 2013 So you need to run a query against your DB2 database, but what software do you need to do that and how do you point that software to your database? There are actually quite a few options that range from simple command line tools to basic GUI (Graphical User Interface) tools to sophisticated reporting writer tools like Cognos. In this article I'll cover command line and basic GUI tools that are free from IBM with DB2. With these tools you can quickly start running queries. Many people will run these queries from their workstation, but if you have direct access to your database server with tools like telnet or ssh you can run the same command line tools there. By default, at least the command line tools get installed with your DB2 server software. To access your databases with these tools from your workstation you will need to download and install either the IBM Data Studio, IBM Data Server Runtime Client or the IBM Data Server Client. You can read about these clients and get download links from my DB2 Clients page. You can see short descriptions here: The IBM Data Server Runtime Client allows you to have command line access where you can type your queries command line or execute queries you have saved in a file. The IBM Data Server Client gives you a GUI interface called the Command Center and the same command line tools as the runtime client.

Upload: sonicefu

Post on 16-Dec-2015

62 views

Category:

Documents


3 download

DESCRIPTION

Running DB2 Queries

TRANSCRIPT

Running DB2 Queries Part 130 October 2010Updated 2 January 2013So you need to run a query against your DB2 database, but what software do you need to do that and how do you point that software to your database? There are actually quite a few options that range from simple command line tools to basic GUI (Graphical User Interface) tools to sophisticated reporting writer tools like Cognos. In this article I'll cover command line and basic GUI tools that are free from IBM with DB2. With these tools you can quickly start running queries.Many people will run these queries from their workstation, but if you have direct access to your database server with tools like telnet or ssh you can run the same command line tools there. By default, at least the command line tools get installed with your DB2 server software.To access your databases with these tools from your workstation you will need to download and install either the IBM Data Studio, IBM Data Server Runtime Client or the IBM Data Server Client. You can read about these clients and get download links from myDB2 Clientspage. You can see short descriptions here:TheIBM Data Server Runtime Clientallows you to have command line access where you can type your queries command line or execute queries you have saved in a file.TheIBM Data Server Clientgives you a GUI interface called the Command Center and the same command line tools as the runtime client.TheIBM Data Studiogives you a GUI interface that is very easy to use.21 January 2011 UPDATE:Optim Development StudioandOptim Database Administratorare now available for free for customers who own any paid edition of DB2/LUW and have current maintenance. They are available on your Passport Advantage site where you get DB2. These are additional Eclipse based GUI tools that provide all of the features of IBM Data Studio plus several more. Optim Development Studio is especially good at helping you generate queries.2 January 2013 UPDATES: Optim Development StudioandOptim Database Administratorhave now been consolidated in to the freeIBM DataStudio 3.1. DB2 v10.1 and later clients or servers will no longer contain Control Center, Configuration Assistance or Command Center. However, some GUI tools are still included such as the Replication Center. The IBM Data Studio is now the GUI tool that should be used for most administration purposes. While you can use the v9.7 Control Center for DB2 10.1 clients, you can not use new features like the INGEST utility from it. Most SQL queries should work from the v9.7 Command Center, but at some future server version, the v9.7 client will stop working.IBM Data StudioIf you are not very familiar with installing and configuring database connections then this is the tool for you. It is a stand-alone tool that allows you to connect to a database and see the tables you want to query and helps you write your queries. You can also easily save your queries into files and easily retrieve them. This tool has many other features for more advanced users such as wrapping queries in web services and a stored procedure builder, but I will leave those topics to a later article. In addition to being very easy to use for the beginner, this application allows you to connect to DB2/zOS, DB2/i (AS400), DB2 on Linux, Unix and Windows (LUW) and Informix. Even the connections to DB2/zOS and DB2/i are free and do not need DB2 Connect! It installs its own JCC driver and makes JDBC type-4 connections to the database. This driver can not be used to connect other applications to the databases. For more information about how to run queries in Data Studio please see this article:Data Studio Update Part 5: Query Building and Editing.IBM Data Server ClientThe Data Server Client is also good for querying the database.Important: See bullet 2 in the 2 January 2013 updates above! It provides both the GUI Control Center/Command Editor that allows you to query DB2/LUW databases and provides all of the command line tools as well. It also comes with theConfiguration Assistantthat is a GUI tool for configuring the database connections and creating ODBC sources when you create those connections. In addition to creating queries in the Command Editor, you can also connect applications like Excel spread sheets to the database using the ODBC source. Many other reporting and query tools can use the connections and ODBC sources you create with the Configuration Assistant. You can invoke the Command Editor either from the Control Center start it by itself from the Windows Start Menu. The Control Center and its components like the Command Editor are being deprecated, meaning that they may not be found in upcoming versions. Only the GUI tools are being deprecated the client is not. Further you should note that the Control Center and Command Editor are not available on UNIX and may not be available on some Windows and Linux server editions since these are strictly meant to be client tools starting in DB2 v9.1. To query DB2/zOS or DB2/i you must be licensed forDB2 Connectand either have it installed or have an available DB2 Connect Gateway.IBM Data Server Runtime ClientThe runtime client is the same as the IBM Data Server Client, except it does not have any of the GUI tools like the Command Editor. However It does have the command line tools that allow you to query the database and the libraries that allow you to connect applications through the database connections and ODBC sources. You just have to configure these items through the command line.Command Line ToolsAll of these tools are available through the Data Server Client and the Data Server Runtime Client. They are:Command Line Processor Command Line ModeCommand Line Processor Interactive ModeCommand Line Processor Plus (CLPPlus)Command Line ProcessorThese tools take as input queries or certain types of commands and return the results to the standard output or screen. These are just regular shell windows with the environment set to find DB2 libraries. On Windows these are Command Windows (DOS windows) and regular terminal shell windows on Linux and UNIX. From the Command Line Processor (CLP) in either mode, you can execute many types of commands, but I will focus mainly on database queries.The CLP in Command Line Mode is just a DOS Window (C:\>) or Linux/UNIX terminal window ($). At these commands you can not only execute regular shell commands like dir or ls, but you can also execute queries with the db2 command. For instance you can say:$ db2 select * from table_xyzorC:\> db2 select * from table_xyzand get back all of the rows from that table. From the CLP Interactive Mode you are already inside of a db2 command shell (db2 => ) so you would just execute the query without typing the db2 part. From the CLP Command Line Mode, you can also execute system commands like db2pd that you can't execute from Interactive Mode or the GUI Command Editor. With both modes you can execute sets of queries that are in a file.Before you can execute a query, you must have the database cataloged (defined to your client) as described by theConfiguration Assistantor other means. When the database is cataloged on your system you give it a name that is often the actual name of the database but you can give it an alias as part of the command. In any case with both CLP modes you must also connect to the database before issuing queries. Therefore, a client with a database defined with the name mydb you would execute the following set of commands if you wanted the results of the two queries in a Linux CLP Command Line Mode window:$ db2 connect to MyDb user MyUserID$ db2 select * from dba_tab where name = 'db2Dean'$ db2 select count(*) from syscat.tablesIf you entered the CLP in interactive mode, you also need to connect as follows:db2 => connect to MyDb user MyUserIDCommand Line Processor Plus (CLPPlus)If you are used to running queries and reports in Oracle using SQL*Plus then you will be right at home using the CLPPlus. This tool allows you to run your queries just as you would under SQL*Plus and has all of the formatting utilities to which you have become accustomed. TheCLPPlus Commandsare also the same as the ones you know and love. For queries, it is your choice whether to run queries under CLP or CLPlus. One is as efficient as the other so you should use the one you like best for queries. CLPlus even allows you to run a subset of CLP commands such and IMPORT and LOAD. To enter clpplus from a DOS Window, you can enter the following command:C:\> clpplus MyUserID@localhost:50000/MyDbIf you start CLPPlus from the windows Start menu then you will need to issue the connect command before you can enter queries:SQL> connect MyUserID/MyPasswd@localhost:50000/MyDBOnce you enter the clpplus command you are in an interactive mode and you will enter your queries at the SLQ> prompt. Don't forget to end each query with the semicolon. Here is an example of connecting with CLPlus and then entering a query:$ clpplusMyUserID@localhost:50000/MyDbConnected to MYDB v 9.7 AS MyUserIDSQL > select * from dba_tab where name = 'db2Dean';EXITThe EXIT breaks you out of the CLPlus. Since you supply the connect string for the database with this command you don't need to catalog the database on your client, so you will not need tools like the Configuration Assistant. If you need to create reports from the command line, then CLPlus is a much better choice than the CLP because CLPlus has a much richer set of formatting commands.Invoking the Command Line ToolsAlthough the CLP can be invoked from a graphical menu on Linux platforms and from the command line in Windows, I usually see folks start it from a terminal window on UNIX and Linux and from the Start Button if running Windows.Under windows you typically push the Start button and then choose Programs or All Programs and you can then choose the mode that you want as shown in this diagram:

This is a screen shot of a Windows XP system with the DB2 v9.7 Data Server Client installed. Different editions of DB2 and different editions of Windows may not look exactly like this, but will be similar. In this diagram you can choose any of the items in the box on the far right to invoke an editor:What you SEEWhat you GET

Command EditorGUI Command Editor. Can also be selected from the Control Center once it is started using:General Administration Tools | Control Center

Command Line ProcessorCLP Interactive Mode

Command Line Processor PlusCLPPLUS

Command WindowCLP Command Line Mode

You can use a similar GUI menu to start the command line tools under some Linux installations and there the DB2 menus will look similar to Windows. However, since people often just use them from a terminal window, I'll go more in depth here on that. Once you have a terminal window, you have to inherit certain DB2 environment variables to be able to run DB2 commands. You do this be executing the db2profile file in the sqllib directory that is under the DB2 instance on the machine. You need to do this whether you are running from the instance owner id or from your own personal user id. For example you would execute:./home/db2inst1/sqllib/db2profileYou would substitute /home/db2inst1 for the actual directory where your DB2 server or client instance lives on the local workstation or server. Don't forget that DB2 database servers always get at least the runtime client, and the Control Center can also be optionally installed on some Windows and Linux server operating systems, but not on any UNIX systems. Also remember to use the dot space syntax used above to inherit the correct profile settings.Once you've set your profile, you can now run the CLP in either mode or run the CLPlus to run queries.Once you are have set the profile under Linux or UNIX or have started the Command Window as shown in the diagram above for Windows, you are ready to start runningCLP Command Line Modecommands as shown in the Command Line Processor section above, for example you can run:db2 connect to MyDb user MyUserIDFurther, to run queries already in a file you can run the command line mode using the -f option to do so:db2 -tvf MyFile.sqlInvoke theCLP Interactive Modeby just typing the command, db2 and hitting enter from the Command Line Mode or Choose the Command Line Process on Windows. The CLP has many other options including ones to turn auto commit on and off. You can see the complete list atOptions List.Once you have set the profile under Linux or UNIX or have started the Command Line Processor Plus as shown in the diagram above for Windows, you are ready to start runningCLPPluscommands as shown in the Command Line Processor Plus (CLPPlus) section above, for example you can run:clpplus MyUserID@localhost:50000/MyDband then start entering queries. To run a query contained in a file execute this:clpplus MyUserID/MyPassWord@localhost:50000/MyDb @MyFile.sql***This article should get you started if you need to review your options for running queries. However, there are many more things that you can do with these tools and I will discuss them in later articles. I am considering topics in those articles that including scripting with the command line tools, cataloging tables from the command line, connecting to DB2 on i and z, and much, much more. Stay Tuned!Running DB2 Queries Part 2 -- CLPPlusBurt Vialpando and Dean Compher21 January 2011With the release of DB2 v9.7 you have a new command line interface called theCommand Line Processor Plusor CLPPlus. This is available on all DB2 v9.7 clients and database servers. It gives the heritage DB2 person a new report generation tool. It gives the person who knows the Oracle SQL*Plus interface a way to query and do some database administration in a syntax they already know. This is especially good for those in a shop that has both DB2 and Oracle because it provides a common query and basic reporting interface for both databases! In this article I'll show you how to get started using the CLPPlus interface and provide several examples.The bulk of this article is taken directly from material created by Burt Vialpando in hisIBM DB2 9.7 Administration for the Experienced Oracle DBAProof of Technology. The figures shown are also lifted directly from his presentation. If your local IBM database sales representative can arrange it, Burt can come to your city and deliver this Proof of Technology to you in person. I have also posted a number of scrips written by Burt in the Files section on mydb2Dean and FriendsdeveloperWorks community page. Please feel free to download them as they are a great way to get started with this tool.We'll start out by giving some simple examples of using CLPPlus. The first thing that you need to do is to start the CLPPlus and connect either from a shell window or from the GUI menu. For more details about connecting, please see my previousRunning DB2 Queries Part 1article. Here are two quick examples connecting to the DB2 sample database:$ clpplus MyUserID/MyPasswd@localhost:50000/sample - or -Start | All Programs | IBM DB2 | DB2COPY1(Defalut) | Command Line Tools | Command Line Processor PlusSQL> connect MyUserID/MyPasswd@localhost:50000/sampleThe sample database comes with every version of the DB2 database server. If you want to try these examples yourself, just log in to any test database server instance and execute thedb2sampl(NO e) command and it will create the sample database for you complete with data. The following examples use tables and other objects in that database, so your results should be similar. Please note that CLPPlus works with all editions of DB2/LUW except the Express-C version.Once you are connected you can run commands or queries. Here are some examples that you may recognize if you are used to using Oracle:Thedescribe employeecommand which is similar to the traditional DB2describe table employeecommand is shown here:

To run operating system (OS) commands from the SQL> prompt you just prefix them with the HOST command, or starting in fp3a you can use the ! as shown in the following two examples:SQL> host dirSQL> ! more db2diag.logFrom within the CLPPlus tool you can do several things with your SQL including running SQL from a file, view previously executed SQL, show the SQL and edit the SQL. These commands and the ones like HOST that I showed above are all described in more detail by clicking the appropriate links on theCLPPlus Commandspage. Here are a few of the commands that you can use for queries with examples after that:Use the START command to execute SQL already in a file or the GET command to just load the SQL file into the buffer without executing it.Show the last SQL command executed using the LIST command.Edit SQL using the CHANGE command or the EDIT commandExecute SQL using the RUN CommandSave the query to a file using the SAVE commandTell CLPPlus to send the output of a query to a file using the SPOOL command or tell it to show the elapsed time for query executionIn the following example a simple query in the file called CLPPlus01.SQL will be executed from the SQL> prompt with the output shown afterwards:start CLPPlus01.SQL

Use the LIST command to display the last SQL command executed or in the buffer:

You can edit the SQL in the buffer by doing simple substitutions with the CHANGE command, for example, SQL> change /salary DESC/salary ASC/or by executing the EDIT command to edit the file in the default editor like Notepad or vi. You must save the file using the editor's save commands as you normally would to have the contents of the buffer changed. Here is an example of using the EDIT commandsSQL> edit

In this case you would select File|Save to save the changes and then exit Notepad to get back to your CLPPLUS where your updated copy of the SQL will be automatically shown. To execute the query, just execute the RUN command at the SQL> prompt.Now that you've verified the results of the query in the CLPPlus window, you can run the query again, saving the output to a file called employee_report.txt using the following commands:SQL> SPOOL employee_report.txtSQL> RUNSQL> SPOOL OFFIn this case the RUN command just runs the query already in the buffer. You don't want forget to turn off the spooling or the results of subsequent work will also be saved to this file. To see the status of things like spooling you can use the show command as follows:SQL> show spoolIt is often important to measure the speed of your queries. You can do this by turning on timing. When this feature is enabled, CLPPlus will show you how much time it took to run your query. When you've spent a significant amount of time getting a query just right you will want to save it to a file too. Assuming that our query is still in the buffer you can time the execution and save the query in this example:SQL> set timing onSQL> runSQL> save updated_query.sqlThis just provides a few examples of running commands and queries in CLPPlus. As I noted earlier, you can see the complete set of commands on theCLPPlus Commandspage and get a description of each command by clicking on it.Reporting and Running CLPPlus from ScriptsSo far we've discussed running commands and queries interactively, but it is often useful to be able to run existing queries from the Operating System (OS) command line or from a script. This is especially true for reporting, so I also briefly discuss reporting features here.You can execute an SQL script file using the CLPPlus command, denoting the input file using the @ symbol. For example:$ clpplus myUser/myPass@serverName:50000/dbName @fileName.sqlHere is a diagram that Burt provided showing what is in each segment:

Just as with the regular CLP, you can have several SQL queries and commands in a file separated by semicolons.A frequent use of scripted queries is for reporting. CLPPlus adds a lot of reporting capabilities to DB2 that are easy and fast to implement when you need to create a good looking report in a hurry. It is also great if you need to create professional reports, but don't have any other reporting tools. It uses the same formatting commands as SQL*PLUS so if you create software that needs to run on both Oracle and DB2 you can create one report that runs on both. If you are familiar with creating reports for Oracle databases and now need to create them for DB2/LUW then there is not much new for you to learn.To see all of the many report formatting capabilities of SQL plus such as defining column headings, defining lines per page, or defining report column lengths visit theSETcommand page. Burt also created some great examples of report formatting that you can copy from mydb2Dean and FriendsdeveloperWorks community page and use for the basis for your first reports. All of these reports operate on the sample database that comes with DB2, so you can run them right away to see what they do. You may need to change ports, hosts, userids or passwords, but they should otherwise work. If you find them useful, please also leave a note on the Message Board section thanking Burt! Here are the files on my community page that I recommend most for reporting examples:CLPPlus03.SQL - Called by the CLPPlus02.CMD DOS shell scriptCLPPlus04.SQL - Run interactively/Uses substitution variablesThe CLPPlus02.CMD file is a DOS batch shell script that provides a good example of configuring the environment for CLPPlus and then executing an SQL file from within the script. You can execute the 04.SQL script from the command line as follows:C:\> clpplusmyUser/myPass@serverName:50000/sample @CLPPlus04.SQLYou will then be prompted for two values. This example shows what you will see and what you should enter:

Unless you change it this script will create a file called CLPPlus04_OUTPUT_REPORT.txt because that is what is defined in the spool command in the script. You can review that file for the report created.Further ExamplesThis article is the second installment of an occasional series that I am writing about how to query your DB2 database. There are several more things that you can do with CLPPlus that are beyond the scope of these articles. However, I have included Burt's examples on my community page. They are well documented, so you can review them and see what they are doing. They primarily show examples of using traditional Oracle query and command syntax on DB2. Examples include using the DECODE and ROWNUM commands, running PL/SQL scripts, Anonymous Block, and DBMS package use, plus other interesting features. You will need to set theDB2_COMPATIBILITY_VECTORregistry variable correctly to use a number of these features.If you want to try out these examples, but don't have a database server you can experiment with, you can just download a free trial version of DB2 from theDB2 9.7 Trial Downloadpage and put it on your Windows or Linux workstation or small server. Another alternative is to get a very inexpensive server in the cloud. See how to do this on myDB2 in the Cloudarticle. Once you have a DB2 v9.7 instance, you can create the sample database db2sampland start running these examples! Regardless of the method you use of getting access to a DB2 v9.7 database, make sure that you are not using the Express-C editionbecause that one does not with with CLPPlus.A very few database administration commands can be run in CLPPLUS, but for most you will need to use the CLP for administering your database.***More and more collateral is being added to the web all of the time about CLPPlus so keep looking. You can even see aYouTube CLPPlushow-to video. It is only 6 minutes, but has lots of great information for getting started. Stay tuned for part 3 of my series of client articles where I'll compare and contrast the various free query and administration tools to help you pick the right one for your purpose. Finally don't forget to visit mydb2Dean and FriendsdeveloperWorks community page for CLPPlus examples and to share insights you have about using the CLPPlus.Part 3 of this sears describes that actual free tools that you can download to query DB2 Databases.

Running DB2 Queries Part 3Dean Compher21 March 2011Updated 2 January 2013There are a variety of different tools that you get complementary with DB2 on Linux, UNIX and Windows (DB2/LUW) that will allow you to query your database and run commands, but how do you choose which one to use? Now that Optim Database Administrator and Optim Development Studio come complementary with DB2/LUW, there are even more choices. In this article, I'll give a brief summary of these tools and give my thoughts on when to use each of them. In some cases this will just be your preference. In some of my earlier articles, I've discussed the packages that contain these tools and where to get them and have even gone more in depth about some of the individual tools and where to get them including:DB2 Clients Connect to your Database - Describes client and driver packages that contain the command line and some GUI ToolsRunning DB2 Queries- Part 1 Describes how to use the CLP and CLPPlus toolsRunning DB Queries Part 2- CLPPlus Describes the new CLPPlus interfaceData StudioCompares and contrasts the GUI Control Center and Data Studio and describes Data StudioI want to take a moment to thank Csar Inacio Martins who wrote to me suggesting this article. If you have ideas about what you want see in future articles, please e-mail me or add a suggestion to the Message Board on mydb2Dean and FriendsdeveloperWorks community page.The tools that I'll compare in this article are:Data Studio (GUI)Optim Development Studio (GUI)Optim Database Administrator (GUI)Control Center/Command Editor (GUI, Deprecated 9.7, Discontinued 10.1)Command Line Processor CLP (Command Line)CLPPLus (Command Line)The complimentary GUI interfaces for running Queries on DB2 are IBM Data Studio, Optim Development Studio, Optim Database Administrator, and the DB2 Control Center. Data Studio, ODA and ODS are the up and coming GUI Clients, but some functions such as the control of Replication are not there. The Control Center has been deprecated, but currently has more functions, especially at the instance level. For more information about these clients see my previous Data Studio article.IBM Data StudioThe IBM Data Studio allows you to connect to DB2 on ALL platforms (LUW, Z, I)withoutDB2 Connect and Informix too. It has a helpful query editor and provides a great way to organize and recall your SQL scripts in the Data Project Explorer. Check out this developerWorks article about theData Studio Query Editor. Among other things the Data Project Explorer provides an expandable menu like Windows Explorer that lets you organize your scripts in a hierarchy or groups and view/edit them by just double clicking. You can also create and debug stored procedures with Data Studio. Data studio allows you to do many database level administration functions like alter table, export, runstats object creation, etc., by right clicking the appropriate object or heading in the Database Explorer. When you execute those administration functions you will be led through a set of menus to choose parameters. At anytime you can view the command being created. Data studio only runs on Windows and Linux and makes a JDBC Type-4 connection to the database. Anyone candownloadData Studio from the web. Two versions are available as described on the download page. If you think that you might want to use Data Sudio with other products later, then I recommend getting the IDE version. The only advantage to the stand alone version is that it takes less space on your hard drive. One other download link available on this download page is the Data Studio Health Monitor. It pretty much does the same thing that the Health Center does in Control Control Center.Data Studio is unable to do some instance level administrative tasks like starting and stopping instances. Data Studio does not talk to the Database Administrative Server (DAS). The DAS is a separate process on the database server that can control database instances. Since Optim Development Studio and Optim Database Administrator have everything in Data Studio and are now free for customers with up-to-date maintenance, I recommend using one of them instead of Data Studio, unless you just need a lightweight query tool. All of these three tools also allow you to create XQuery XML queries. Please also see theIBM Data Studio Overviewwhere you can drill down into more detailed information.Optim Development StudioOptim Development Studio and Optim Database Administrator have now been consolidated in to the free IBM Data Studio 3.1.Optim Development Studio (ODS) has everything in IBM Data Studio described above and several additional features, but with the same instance administration limitations. ODS is now free with DB2/LUW as long as your maintenance is up to date, but requires a separate download from Passport Advantage, the same place you would download DB2 and other licensed products. Please note that ODS and its Activation Kit are imbedded in the set of products under the main DB2 collection and only under the ones for Linux and Windows. It also has the same look and feel of Data Studio and other OPTIM products because they all use the same views like Data Project Explorer and Data Source Explorer, and uses the sameQuery Editor. While Development Studio does many things useful to the Java developer. Like generating methods for several tables at once, those things are beyond the scope of this article. One of the best parts of ODS is that it better facilitates collaboration between developers and DBAs during Java development projects. For the DBA it does all of the database administration tasks described above under Data Studio, plus it has other useful features. For example, you can run a Java application in ODS and see performance metrics about each query issued during the run or set of runs. In reality, the Java developers will typically run the application under ODS on her own workstation capturing the correct information, export the project and send it to the DBA where he can review the queries. Once the DBA has the ODS/pureQuery output the queries can be sorted by metrics like longest elapsed time or most CPU time and each interesting query can be explained right in the tool. Further, the ODS user can often see the Java method and line number from which the SQL statement originates. How to do these and other functions is explained in the 5-partOptim Development Studioarticle. While the title of this article starts with, What's New and Cool... it really gives a nice overview of the product. Make sure to click through to all 5 parts. Please also see theIBM Optim Development Studio Overviewwhere you can drill down into more detailed information.Optim Database AdministratorOptim Development Studio and Optim Database Administrator have now been consolidated in to the free IBM Data Studio 3.1.Optim Database Administrator (ODA) has everything in IBM Data Studio described above and several additional features, but with the same instance administration limitations. ODS is now free with DB2/LUW as long as your maintenance is up to date, but requires a separate download from Passport Advantage, the same place you would download DB2 and other licensed products. Please note that ODA and its Activation Kit are imbedded in the set of products under the main DB2 collection and only under the ones for Linux and Windows. It also has the same look and feel of Data Studio and other OPTIM products because they all use the same views like Data Project Explorer and Data Source Explorer, and uses the sameQuery Editor. ODA is a great tool for the DBA who needs to change databases, while preserving the data, permissions, indexes and other dependent objects even when tables need to be dropped and recreated. For more information on ODA, please visit theODA Information Center. A good place to start is the Learn More link.ODA allows you to reverse engineer the database into the tool, make changes to the objects using easy to use object editors and then when you are done it will generate a script to implement those changes in your database. When run, the script will capture all objects and permissions in the current database, keep a copy of data in the form that you dictate like a shadow tables or export/import/load processes, and drop/create or alter objects as needed. For a large complex change, this can save weeks of work and increase the quality of the change on implementation night. ODA will also generate a script to back out all changes in case something goes wrong. In addition to implementing changes that you input, ODA can also compare two databases, and generate a script to make the structure of one database like the other, preserving all data in the database being changed. This is great where you have a months-long development project where you are making several changes to the test database over time. At the end of the project, you can compare test to production, and tell ODA to generate a script to make the production database schema look just like the test database, while preserving the production data. ODA can also be used to generate scripts to copy databases or portions of them. Finally if you haveInfosphere Data Architect, our data modeling tool, you can compare a model to a database and have ODA generate the change script to make the database look like the model.You can have both Optim Database Administrator and Optim Development Studio on the same workstation. If you install them such that you shell share them, then you can do all functions provided by the combination of tools from one window. Adding one after the other is installed just adds expands the tools available in the same window. This is all part of IBM'sIntegrated Toolsapproach. Data Studio, ODA and ODS only run on Linux and Windows and are primarily designed to run on a workstation as opposed to installing directly on a server.Control Center and Command EditorStarting with DB2 10.1, the Control Center and Command Center are no longer included in any clients or servers. However, some GUI tools are still included such as the Replication Center. The IBM Data Studio is now the GUI tool that should be used for most administration purposes. While you can use the v9.7 Control Center, you can not use new features like the INGEST utility from it. Most SQL queries should work from the v9.7 Command Center, but at some future server version, the v9.7 client will stop working. TheControl Centerand its component Command Center have been around a long time, but have been deprecated with the release of DB2 v9.7. This means that they are no longer being improved, and at some point they will not work with new versions of DB2. Command Editor is a basic GUI SQL editor and is a component of Control Center that can be invoked from within Control Center or from the command line or GUI menu. Control Center allows you to perform all database and instance level administration tasks. You need to have theDASrunning on your database servers to allow it to stop and start your instances and some other instance level administration tasks, but database object commands can be executed without the DAS. You can perform all object related administration tasks like alter table, export, runstats object creation, etc., by right clicking the appropriate object or heading in left pane of the window that shows databases and objects under them. Using the Command Editor you can run any SQL statement and some DB2 commands.You can install the Control Center on your Windows or Linux server from the Data Server Client as described inDB2 Clients Connect to your Databaseor optionally when installing DB2 Connect or a DB2 Database Server. Starting in DB2 v9.1, Control Center no longer installs on any flavor of UNIX. Unless you need one of the functions that are not in Data Studio, ODA or ODS, I recommend that you use one of those tools instead since Control Center will go away sometime in the future. You can start the Control Center either from the Linux or Windows GUI menus, or from an OS shell window using the db2cc command as long as your environment is configured.Command Line ProcessorThe CLP is a command line interface that is always installed with all DB2 servers, clients, and even with DB2 Connect. It can be executed locally on a server through an SSH or Telnet window, or you can execute it on your workstation and then connect to the database server you desire. You would typicallycatalog the databasebefore connecting to it from a client (i.e., the CLP on your workstation). I consider the CLP the workhorse for database administration. It is typically run by just logging into a Linux or UNIX server through something like Telnet or SSH, or on Windows by taking remote control of the server and then opening a Command Window. These CLP windows are really just a regular shell window on the OS with DB2 specific environment variables set such as the path to the DB2 libraries. You just need to inherit the /sqllib/db2profile to set these. Once you have this and a login to the database with appropriate authorities you can run all queries, DB2 Commands (db2 list applications) and system commands (db2level).While it is true that I am a line command nut, I can objectively say that the CLP is hands-down the best tool for administration. It always works when you can get a login to the database server and it is fast. I visit a lot of customers, and knowing the CLP means that I can help with the database regardless of whether anyone has installed a GUI client, has xWindows working or can make a client connection to the database. Also I've created SQL scripts for many activities and find it less time consuming to just run them from the CLP than trekking through a series of GUI menus to do what I need to do. Further, in an attempt to make things easier for you by making certain assumptions, GUI's often make troubleshooting more difficult. First, you don't always know what the GUI client is really executing against the database, so you don't always know what you are actually troubleshooting. Secondly, GUI's sometimes give some generic error message that they generate and hide or truncate the real error codes and messages actually coming from the database. When you use the CLP, you know exactly what is being executed and get the full, raw messages and codes from the database. Please do not construe this to mean that I don't use GUI tools -- on the contrary, I find them very useful and they can save a lot of work. The ones that have a button to show you the SQL or other commands being generated are great because they save you the trouble of getting the syntax exactly right, and you can then paste it into your script that can be executed in the CLP over and over.The CLP is always invoked by the command db2 and can be run in a line command mode or in interactive mode as described inRunning Queries- Part 1. On Windows or a Linux GUI you can directly enter the CLP interactive mode by choosing the Command Line Processor from the DB2 submenu (under the Start button on Windows), but this just starts a regular DOS window or Linux shell window that runs the db2 command for you to get you into the CLP interactive mode. You run the line command by issuing the db2 command followed by a query, command, or the -f option and providing an input file that contains one or more commands or queries. I generally prefer using the line command mode, just because I like combining shell utilities like the pipe |, file redirect > or more with my queries.CLPPlusCLPPlus or Command Line Processor Plus is similar to the CLP and lets you run any queries you like. I have described it in a previous articled called, .Running DB2 Queries Part 2 CLPPlus.CLPPlus allows those familiar with Oracle's SQL*Plus syntax to generate queries and run PL/SQL in a way that they already know and has great reporting features that allow you to quickly and easily format query output into a report. The CLPPlus does not run most system commands like db2level or db2ilist and does not support most CLP commands like list tablespaces show detail.Administrative APIsAnother way to query the DB2/LUW database and perform administrative tasks is through programming languages such as C, C++, REXX or COBOL. There are Application Programming Interfaces already built for most of the commands you would execute from the command line or script. I don't know much about this, but there are good explanations and lots of examples of using them in theAdministrative APIsection of the Information Center. Please make sure to scroll all the way down when you get tho this page for lots of links that show information about many facets of this interface.***I hope that this article has been useful for determining which complimentary tool is right for you and when you should use each. Please add feedback to mydb2Dean and FriendsdeveloperWorks community page with additional insights that you believe may help others who read this article. Also if you are on Facebook, please Like mydb2Deanpage.

Running DB2 Queries Part 4Dean Compher29 April 2011Updated 25 November 2011There are a lot of useful things that you can do with the query tools that come with DB2 on Linux, UNIX and Windows. With these tools you can execute queries directly on the server or the tools can run on your workstation and act as a client. There can be subtle differences in the responses you get depending on where the tool is actually running. In this article I'll discuss those differences and conclude with some interesting examples of how you can use the facilities including some scripting examples. I like scripts, because once I've saved them, I can use them over and over without having to figure out a GUI menu every time. In other articles I've described other aspects of the client that may be helpful as you read this article including:DB2 Clients Connect to your Database - Describes client and driver packages that contain the command line and some GUI ToolsRunning DB2 Queries- Part 1 Describes how to use the CLP and CLPPlus toolsRunning DB2 Queries Part 2- CLPPlus Describes the new CLPPlus interfaceRunning DB2 Queries Part 3 -- Compares the various DB2 client tools with each other.Data StudioCompares and contrasts the GUI Control Center and Data Studio and describes Data StudioIt is important to note that there are three categories of things that you can execute in DB2:Queries- select * from table_aDB2 Commands- list node directory or get dbm cfg that are run from CLP window or other interface that typically also allows queries.DB2 System Commands- db2ilist or db2support that are like any another command you can issue at the OS command line like a dir or ls command. Since these are executable files and not something processed by the DB2 client, you generally can't type them into a GUI query tool. Instead, they can be invoked by clicking on the correct menu options in the GUI tools.Before I get into the discussing your options it is important to note that there are some differences between running these commands locally on the database server and running them as a client from your workstation making a client connection to the database. These differences primarily occur for commands that get information from- or make changes to- the instance. For example, queries will always behave the same because you connect to a database that executes the query. However, a number of DB2 Commands and System Commands operate on the instance that is running your current CLP. So for example if you execute the CLP on your workstation and connect to a database on a server, and your run the command db2 list node directory you will see the nodes that have been cataloged on on your workstation, even if you previously connected to a remote database (db2 connect to remote_db). The same is true for system commands. For example if I run thedb2ilistcommand on my workstation, I will only see instances created on my workstation and not any of the instances on the server to which I am connected. There are exceptions though, because some commands are created to be run on a client and connect to a database. In general these commands will have a parameter to specify a database name or will not work unless you already have an active connection to a database. Examples include the db2 export ... command that will only work if you have connected to a database, and the db2expln command that has the -d option to explain a query against a particular database.Considering that almost no one can get their hands on a server console anymore, I want to clarify what I mean by server vs. client in the preceding paragraph. By server vs. client I mean where the library exists from which the command is executed. So if you have the Data Server Client installed on your workstation and you execute the db2 connect to my_db command in a CLP window to connect to a database on a remote server then you are making a client connection to the database, but the db2 command is actually executing from a library on your workstation. In this case you are executing a a command such as db2 or db2ilist on your local machine. However, many DBA's can access a remote database server directly. For Linux and UNIX database servers this is often done using a Telnet or SSH window. In these cases you are actually typing commands like db2 or db2ilist on your own keyboard, but the commands are actually executing objects in the libraries that live on the remote server like they would for the ls or pwd command. Therefore, if I open a CLP line command window on my laptop and also an SSH window where I connect to a remote server, and I connect to the same database on both, when I issue the db2ilist command on both I will see different results!This is a good place to talk about the db2cc DB2 system command that starts the DB2 Control Center. Most people starting the Control Center on a Windows workstation will start it from the menus under the Windows Start button, but you can also issue the db2cc command from a CLP window to start the CC. As of DB2 v9.1 it no longer executes directly any UNIX systems. Many prefer to execute the GUI on their workstation and connect to a database. However, you can still use this command and the others like the ones for Task Center and Replication Center executing directly on Linux and Windows database servers. If you want to actually have db2cc executing on your server and see it on your workstation, then you would connect to the server using your favorite line command window like SSH and then issue the db2cc command. For this to work you need to to have xWindows working on the server and an appropriate environment configuration and an X client like Hummingbird on your workstation to see the Control Center GUI. The same considerations apply about server vs. client execution apply for running the db2cc command on your workstation vs. the server.It has been my experience that everyone who administers DB2 directly on a Windows server either does all of their administration from the client installed or their workstation or takes remote control of the server and sees the desktop of that server. Windows servers also allow the db2cc command to be executed. However, most people that have access to a UNIX or Linux server typically get a login and use SSH or Telnet to connect and get only a character based interface. If you are logging on as the instance owner, then your environment will generally be ready to go to execute DB2 commands because the db2profile command gets executed when you logged in. However, if you log in to the server as a different user id, you can query and administer the database without becoming the instance owner though su or sudo. You just need to inherit the db2profile environment configuration with a command such as:./home/db2inst1/sqllib/db2profileassuming that the instance home is /home/db2inst1. Also don't forget the dot space in front of the path so that you actually inherit the environment. Once you have this environment configured from your personal account on the server, you are ready to issue commands like db2 connect to db_name without becoming the instance owner. Even if you su or sudo to the instance owner you may still find that you need to configure the profile.When you are logged into a server as the DB2 instance owner on that server, you can connect to the databases in that instance with out specifying a user id. However, whenever you connect to a database from any client or from a different local user on the client then you need to specify the userid and password. In the CLP on your workstation you can connect to a database on a server using theconnectcommand as follows:C:\> db2 connect to db_name user user_idIn this case I did not specify the password, so I would be prompted for it. When you are running the CLP on your workstation making a connection to a remote database, then you need to CATALOG the node and database on your server or add a db2dsdriver.cfg file. Cataloging just means that you have defined all of the information needed to connect to the database on your client, and gave that definition a name. In the example above that name is db_name. Most people use the actual name of the database, but you can make it anything you want. You can run the catalog commands inthe CLP or you or you can use theConfiguration Assistant. Just remember though, that the entries will be made on the machine actually executing the CLP or CA code as described in earlier paragraphs.You can update thedb2dsdriver.cfgfile with your favorite editor to add database connection information. It is an XML file that can also be used for several other client configurations as well including pureScale. It allows you to create connections for your client and e-mail it to your users instead of cataloging databases on each client. Here are some important points: V9.5 fp3 introduced it for the DS Driver V9.7 fp3a introduced it for CLI clients (e.g. Control Center) V9.7 fp4 introduced it for .NET clients. Can be used for OCBC, CLI, .NET, OLE DB, and open source (PHP or Ruby) connectionsFind a sample of the file for V9.7 fp3 and later in a file called db2dsdriver.cfg.sample after you install your Data Server (Runtime) Client or Data Server Driver. Ive also included some samples of the file in the Files section at the bottom of mydb2Dean and Friends Communitypage. To validate your file use the db2cli tool to see if you have errors.It is important to note that some tools like IBM Data Studio, Optim Database Administrator and Optim Development Studio and other Eclipse based clients use a JDBC type-4 connection and the database does not need to be cataloged in the database directory. In these tools you would create the connection by right-clicking the Database Connections heading in the Data Source Explorer view, choosing New from the menu and following the wizard to create the connection:

The eclipse based tools can also be run on Windows and Linux, but not UNIX. They can also be run locally on a server like control center, but are more typically run on a workstation client. For more information on Data Studio, ODA and ODS, please seePart 3 of this series.So now I'll actually get into discussion of running queries, DB2 Commands and DB2 System Commands using the CLP. The preceding discussion was needed to show options that can be used instead of the CLP and the differences between executing a command on a server vs. a client of the database such as your workstation.The good news about queries is that they always behave the same running on the server as they do on a client. They always operate on the database to which you are connecting. One nice thing about executing queries through the CLP is that you can easily take control of what it is doing through options that you choose. You should note that a minus (-) sign in front of an option turns it on and a plus (+) turns it off. For a complete list of options and their use, see theCLP Optionspage. Some of the more commonly used options are:ffilenameUse filename as input of command(s)/query(s) instead of looking for a query or going into interactive mode

tOften used with -f to say that the semicolon (;) is separates commands

vVerbose Echo command text to standard out.

cAutocommit. Useful if you want to hold a lock. On by default.

-lfilenameLog commands into a history file. Most useful in an interactive session.

For example, the following command:db2 +c -tvf my_file.sqlWould execute the queries in the file my_file.sql (-f), expecting those commands to be separated by semicolons (-t), echoing the commands in my_file.sql to the output (-v), and continuing to hold locks after query completion (+c). In this case, you could test to see what happens in a locking scenario by opening a second CLP window and executing commands that try to update those same rows. This is useful to see what happens in a lock timeout situation or to test lock monitoring in your database monitoring tool like Optim Performance Manager. Locks will continue to be held until you explicitly issue a COMMIT or ROLLBACK command.Scripting is great because it saves you lots of time, by having commands and queries already written that you use a lot like taking snapshots and is useful in automating maintenance functions like backups. Another thing that is great about scripting is that you can generate other scripts based on dynamic data in the database. For example, I once needed to script the RUNSTATS command to run weekly for a database system where tables were frequently added and I didn't want to have to remember to modify the RUNSTATS script each time a table was added. As you may recall, RUNSTATS takes a table name as input. I wrote the following query to generate the RUNSTATS commands that I would then execute as part of the script. Here it is:select 'RUNSTATS ON TABLE ' || VARCHAR(RTRIM(CREATOR),8) || '.' || NAME || ' WITH DISTRIBUTION AND DETAILED INDEXES ALL SHRLEVEL CHANGE;' from sysibm.SYSTABLES WHERE TYPE = 'T' AND CREATOR IN ('PROD1', 'PROD2') AND NAME NOT LIKE 'EXPLAIN%' AND NAME NOT LIKE 'ADVISE%' ORDER BY CREATOR;I said I incorporated this query (in a file called runstats.sql) into a shell script that then ran the output of this query. One nice thing about shell scripts is that you can check the return code from from your query and report problems. This is especially important for commands executed on a database because sometimes there can be locking or other problems. The CLP is no different and you can see all of its return code meanings on theCLP Return Codespage. Here is a portion of the script where I call the RUNSTATS query (runstats.sql) above and then execute its output:TOLIST="[email protected] [email protected]"SUBJF1="ERROR DB2 CREATE RUNSTATS FAILED"db2 -tf /db2inst1/runstats.sql | grep RUNSTATS > /db2inst1/runstats2.sqlrc=$? if [[ ${rc?} -ne 0 ]] then echo "Return code = ${rc?}" mailx -s "${SUBJF1?}" "${TOLIST?}" < /db2inst1/runstats.log db2 terminate exit -1 fi db2 -tvf ${BASEDIR?}/bin/runstats2.sqlI posted both the runstats.sql and the full korn shell runstats.sh that calls it on mydb2Dean and Friendscommunity in the Files section. Please feel free to download and use them. This type of scripting where you generate scripts with a query that combines command literals and database data has a lot of utility. If you have any Windows/DOS batch scripts that call DB2, please add them for others who may find them useful.***I hope that you found this discussion of db2 clients useful. Please like my Facebook db2Dean page atfacebook.com/db2deanand add any feedback about what you liked or what I can improve. You don't have to be a member of Facebook to add comments. I can only make things better with your help!