0% found this document useful (0 votes)
51 views

SQL For The System Administrator

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views

SQL For The System Administrator

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

SQL for the System Administrator

Power Systems 2015


Scott Forstie
[email protected]
DB2 for i Business Architect

For…

1 © 2015 IBM Corporation SQL for the System Admin


Commands, APIs and tools – consider the options

• IBM i has a long history of creating Commands and APIs, so much


so that we frequently conclude that further investment in these
interfaces is the appropriate approach to deliver new capabilities to
our customers

• The subject of this presentation is to explain the role of SQL based


interfaces to allow non-DB2 for i products and components to
understand that an alternative / additional choice exists

• Development Cost, Value to the customer and Risk are the important
factors to consider for any enhancement

2 © 2015 IBM Corporation SQL for the System Admin


Commands, APIs and tools – Why consider SQL?
• Even though IBM i customers are used to commands and APIs, they
are not always the easiest interfaces for customers to utilize
(especially if from a client or the web).

• In many cases, customers are required to write specialized programs


to exploit a new IBM i command or API.

• Across the industry, SQL is recognized as a standardized and easy


language to access the database. SQL skills are either commonplace
or customers have a desire to do more with SQL.

• SQL as a language construct does not need to be limited to database


topics.

• SQL can be used on IBM i to easily extract deep details on non-


database topics. This presentation contains proof of this point.

3 © 2015 IBM Corporation SQL for the System Admin


Commands, APIs and tools – Why consider SQL?

• With SQL-based options, consider which interface provides the best


“tool for the task”

• Customer feedback SQL based interfaces has been very positive

• Besides being easy to use, SQL queries can be used for:


– Selection (WHERE clause)
– Ordering
– Grouping
– Joining
– Top ‘n’ results
– IN, LIKE, NOT, and more…

Unleash the power of the DB2 for i query engine

4 © 2015 IBM Corporation SQL for the System Admin


Where to start? Get educated
• Understand the SQL coding environments:
RUNSQL, RUNSQLSTM, Run SQL Scripts, STRSQL, CRTSQLxxxx,
ODBC, JDBC, PHP, DRDA, etc…
• Understand the query engine and optimizer options:

• Understand the SQL coding options:


Explicit 3-part names, Implicit 3-part names, INSERT with remote
subselect, CREATE TABLE with remote subselect, etc...
• Keep the SQL Reference close by
• Like other crafts… with repeated study and practice, your skills will
improve

5 © 2015 IBM Corporation SQL for the System Admin


New to SQL? Use Navigator’s Run SQL Scripts
• Powerful, graphical interface
IBM i Navigator (aka System i Navigator)
IBM i Access Windows Service Pack
7.1 – SI53809  TR9 timed enhancements

Product Download Site:


www-03.ibm.com/systems/power/software/i/access/windows_sp.html Right click
Next Planned Update…June, 2015

6 © 2015 IBM Corporation SQL for the System Admin


New to SQL? Use Navigator’s Run SQL Scripts
• Insert from Examples…

No need to start from scratch.


Save and reuse useful scripts.

7 © 2015 IBM Corporation SQL for the System Admin


SQL catalogs  TCP/IP Services

TCP/IP Services

8 © 2015 IBM Corporation SQL for the System Admin


QSYS2.TCPIP_INFO – view

Client/server identification, logging and other instrumentation is possible using SQL.


The TCPIP_INFO view returns detailed information for the current connection.

SELECT * from QSYS2.TCPIP_INFO;

Columns which don’t exist on IBM i 6.1:


SERVER_IP_ADDRESS and SERVER_IP_ADDRESS_TYPE

9 © 2015 IBM Corporation SQL for the System Admin


TCPIP_INFO – example usage

• Well defined port numbers –


http://www-01.ibm.com/support/knowledgecenter/ssw_ibm_i_72/rzajr/rzajrservicesandports.htm?lang=en

Now it’s possible (and easy) to deploy interface specific logic with SQL

10 © 2015 IBM Corporation SQL for the System Admin


TCPIP_INFO – Trigger example

This trigger can have conditional logic when running within a QZDASOINIT job.

Varies by the caller 

11 © 2015 IBM Corporation SQL for the System Admin


SYSIBMADM.ENV_SYS_INFO – view

• SYSIBMADM/ENV_SYS_INFO catalog returns information about the current server


• This is a DB2 family compatible administrative view

12 © 2015 IBM Corporation SQL for the System Admin


SQL catalogs  Program Temporary Fix (PTF)

PTF Services

13 © 2015 IBM Corporation SQL for the System Admin


QSYS2.GROUP_PTF_INFO – view

Explore the catalog columns and detail…


SELECT * FROM QSYS2.GROUP_PTF_INFO;

14 © 2015 IBM Corporation SQL for the System Admin


QSYS2.GROUP_PTF_INFO – view
• Use SQL to interrogate PTF Group information
• Alternative to the Work with PTF Groups (WRKPTFGRP) command
• Since this command has no OUTPUT(*OUTFILE) capability, the
command is not easily consumable from a program

-- What PTF Groups will change on the next IPL?


SELECT * FROM QSYS2.GROUP_PTF_INFO
WHERE PTF_GROUP_STATUS = ‘APPLY AT NEXT IPL’
ORDER BY PTF_GROUP_LEVEL DESC;

-- What is the most recently installed CUM?


SELECT MAX(PTF_GROUP_LEVEL) AS CUM_LEVEL FROM
QSYS2.GROUP_PTF_INFO
WHERE PTF_GROUP_NAME IN (‘SF99610’,‘SF99710’)
AND PTF_GROUP_STATUS = ‘INSTALLED’;

15 © 2014 IBM Corporation SQL for the System Admin


QSYS2.PTF_INFO – view
• Interrogate individual PTF information using SQL
• Data returned is similar to the QpzListPTF() API output
• Use SQL to formalize prerequisite checks within software products

-- I’m about to IPL, will the IPL impact PTF state?


SELECT PTF_IDENTIFIER, PTF_IPL_ACTION, A.*
FROM QSYS2.PTF_INFO A
WHERE PTF_IPL_ACTION <> 'NONE‘;

16 © 2015 IBM Corporation SQL for the System Admin


QSYS2.PTF_INFO – view

-- Which PTFs are loaded, but not applied?


SELECT PTF_IDENTIFIER, PTF_PRODUCT_DESCRIPTION, A.*
FROM QSYS2.PTF_INFO A
WHERE PTF_LOADED_STATUS = 'LOADED'
ORDER BY PTF_PRODUCT_ID;

17 © 2015 IBM Corporation SQL for the System Admin


SYSTOOLS.GROUP_PTF_CURRENCY View
SELECT * from SYSTOOLS.GROUP_PTF_CURRENCY
WHERE PTF_GROUP_RELEASE = ‘R720’
ORDER BY ptf_group_level_available -
ptf_group_level_installed DESC;

Current or PTF Group Level Level Date that


behind on Info installed available IBM last
service? on this from IBM updated
partition this group

18 © 2015 IBM Corporation


SYSTOOLS.GROUP_PTF_CURRENCY View

http://www-912.ibm.com/s_dir/sline003.nsf/PSPbyNumL.xml?OpenView&count=500

XML
namespace
&
structure

19 © 2015 IBM Corporation


SYSTOOLS.GROUP_PTF_CURRENCY View

Study the XML structure to define the data to the HTTP function.
HTTPXML document
structure

TCP/IP Enablement:
Enablement
‘www-912.ibm.com’ maps to 129.42.160.32
IBM i TCP/IP configuration Technote:
http://www-01.ibm.com/support/docview.wss?uid=nas8N1018980

White papers:
• https://ibm.biz/XMLandDB2fori Developer
• https://ibm.biz/HTTPandDB2fori
resources
20 © 2015 IBM Corporation
SQL catalogs  Journal Services

Journal Services

21 © 2015 IBM Corporation SQL for the System Admin


QSYS2.JOURNAL_INFO – View
• Use SQL to retrieve detail for local & remote journals
• Information from QjoRetrieveJournalInformation() API, RJRN0100 format.
• The view returns Key 1 & 3 information, one row == information about one journal.

-- Which remote journals are the most heavily used?


SELECT JOURNALED_OBJECTS, A.* FROM QSYS2.JOURNAL_INFO A
WHERE NUMBER_REMOTE_JOURNALS > 0 AND JOURNALED_OBJECTS
IS NOT NULL
ORDER BY JOURNALED_OBJECTS DESC;
-- Journals nearing the limit of journaled objects?
SELECT * FROM QSYS2.JOURNAL_INFO WHERE
JOURNALED_OBJECT_LIMIT = '*MAX250K' AND
JOURNALED_OBJECTS > 200000;
22 © 2015 IBM Corporation SQL for the System Admin
QSYS2.JOURNAL_INFO – View

• Use this new source of information to achieve better journal management


• Recognize conditions that require attention

-- Remote journals that fell behind this week?


SELECT MAXIMUM_TIME_BEHIND, MAXIMUM_BEHIND_TIMESTAMP,
ESTIMATED_TIME_BEHIND, TOTAL_SIZE_JOURNAL_RECEIVERS,
RTRIM(ATTACHED_JOURNAL_RECEIVER_LIBRARY) CONCAT '/' CONCAT
RTRIM(ATTACHED_JOURNAL_RECEIVER_NAME) AS JrnName, A.*
FROM QSYS2.JOURNAL_INFO A WHERE
MAXIMUM_BEHIND_TIMESTAMP > CURRENT TIMESTAMP - 7 DAYS AND
MAXIMUM_TIME_BEHIND > 0 AND MAXIMUM_TIME_BEHIND IS NOT NULL
ORDER BY MAXIMUM_TIME_BEHIND DESC FETCH FIRST 10 ROWS ONLY;

23 © 2015 IBM Corporation SQL for the System Admin


QSYS.DISPLAY_JOURNAL() – UDTF

• Use SQL to extract data from journals


• Either call the UDTF directly or use IBM i Navigator

• Why use these capabilities over the green screen commands?

 Isolate detail from complex data, efficiently


 Automate frequent audit analysis
 Add logic to applications
 Leverage the SQL Query Engine (SQE) to order, group,
join, transform journal based data

24 © 2015 IBM Corporation SQL for the System Admin


QSYS2.Display_Journal – User Defined Table Function
Before 7.2 (must specify 15 parameters):
SELECT journal_code, journal_entry_type, object, object_type, X.*
FROM TABLE (
QSYS2.Display_Journal(
'PRODDATA', 'QSQJRN', -- Journal library and name
'', '', -- Receiver library and name
CAST(null as TIMESTAMP), -- Starting timestamp
CAST(null as DECIMAL(21,0)), -- Starting sequence number
'', -- Journal codes
'', -- Journal entries
'',‘’,'',‘', -- Object library, Object name, Object
type, Object member
‘SCOTT', -- User
'', -- Job
'' -- Program
) ) AS x
ORDER BY entry_timestamp DESC;
With 7.2 (leverage the optional parameters):
SELECT journal_code, journal_entry_type, object, object_type, X.*
FROM TABLE (
QSYS2.Display_Journal(
'PRODDATA', 'QSQJRN', -- Journal library and name
“USER” => ‘SCOTT’ -- User
) ) AS x
ORDER BY entry_timestamp DESC;

25 © 2015 IBM Corporation SQL for the System Admin


DISPLAY_JOURNAL()  Who deleted data?
-- Which rows were deleted from TOYSTORE5/SALES table this week?
select ENTRY_DATA,ENTRY_TIMESTAMP,JOURNAL_ENTRY_TYPE,COUNT_OR_RRN
as ROW_DELETED,"CURRENT_USER", RTRIM(JOB_NUMBER) CONCAT '/'
CONCAT RTRIM(JOB_USER) CONCAT '/' CONCAT RTRIM(JOB_NAME) AS
Qualified_Job_Name from table (
QSYS2.Display_Journal(
'TOYSTORE', 'QSQJRN', -- Journal library and name
STARTING_TIMESTAMP => CURRENT TIMESTAMP - 7 DAYS,
JOURNAL_ENTRY_TYPES => 'DL',
OBJECT_LIBRARY => 'TOYSTORE',
OBJECT_NAME => 'SALES',
OBJECT_OBJTYPE => '*FILE',
OBJECT_MEMBER => 'SALES'
) ) as x
order by entry_timestamp desc ;

26 © 2015 IBM Corporation SQL for the System Admin


DISPLAY_JOURNAL()  What did they delete?
-- What data was deleted from PRODDATA/SALES table this week?
select
cast(cast(substring(entry_data,610-610+1,10) as VARCHAR(10) for bit data) as DATE) AS
SALES_DATE,
cast(cast(substring(entry_data,622-610+1,15) as VARCHAR(15) for bit data) as
varchar(15) ccsid 37) as SALES_PERSON,
cast(cast(substring(entry_data,638-610+1,15) as VARCHAR(15) for bit data) as
varchar(15) ccsid 37) as REGION,
cast(cast(substring(entry_data,655-610+1,4) as VARCHAR(4) for bit data) as varchar(4))
as SALES
from table (
QSYS2.Display_Journal(
'TOYSTORE', 'QSQJRN', -- Journal library and name
STARTING_TIMESTAMP => CURRENT TIMESTAMP - 7 DAYS,
JOURNAL_ENTRY_TYPES => 'DL',
OBJECT_LIBRARY => 'TOYSTORE',
OBJECT_NAME => 'SALES',
OBJECT_OBJTYPE => '*FILE',
OBJECT_MEMBER => 'SALES'
) ) as x
order by entry_timestamp desc;

27 © 2015 IBM Corporation SQL for the System Admin


Navigator  What data was deleted?
Schemas  Journals  View Entries  Enter Filter Criteria
Journal Viewer finds the file and uses the file format to decompose the data!

28 © 2015 IBM Corporation SQL for the System Admin


SQL catalogs  Work Management Services

Work Management Services

29 © 2015 IBM Corporation SQL for the System Admin


QSYS2.GET_JOB_INFO() – user defined table function

• GET_JOB_INFO() accepts the jobname as input and returns a single row result
table containing detail about that job.
• Enhanced with TR8:
• Use ‘*’ to return detail on the current job
• Current (or most recent) SQL Statement text returned

-- Get job information for the current job


select a.* from table(qsys2.get_job_info('*')) a;

-- Get job information for the current job


select a.* from table(qsys2.get_job_info('803868/Quser/Qzdasoinit')) a;

30 © 2015 IBM Corporation SQL for the System Admin


QSYS2.SYSTEM_VALUE_INFO – view

• The new view return the same data as the Retrieve System Values (QWCRSVAL) API
• *ALLOBJ or *AUDIT special authority is required to retrieve the values for QAUDCTL,
QAUDENDACN, QAUDFRCLVL, QAUDLVL, QAUDLVL2, and QCRTOBJAUD
(‘*NOTAVL’ or -1 are returned when accessed by an unauthorized user):
Catalog definition:
SYSTEM_VALUE_NAME VARCHAR(10) – Name of the system value
CURRENT_NUMERIC_VALUE BIGINT – System value when binary data is returned
CURRENT_CHARACTER_VALUE VARGRAPHIC(1280) – System value when character data is returned

-- Examine the system values related to maximums


SELECT * FROM QSYS2.SYSTEM_VALUE_INFO
WHERE SYSTEM_VALUE_NAME LIKE '%MAX%'
ORDER BY SYSTEM_VALUE_NAME;

31 © 2015 IBM Corporation SQL for the System Admin


QSYS2.SYSTEM_VALUE_INFO – view

DECLARE GLOBAL TEMPORARY TABLE SESSION . Remote_System_Values


( SYSTEM_VALUE_NAME,CURRENT_NUMERIC_VALUE,CURRENT_CHARACTER_VALUE )
Remote 3-part
AS (SELECT * FROM X1423P2.QSYS2.SYSTEM_VALUE_INFO) WITH DATA
DGTT
WITH REPLACE; statement

SELECT 'LP13UT16' AS "System Name",


A.SYSTEM_VALUE_NAME,A.CURRENT_NUMERIC_VALUE,A.CURRENT_CHARACTER_VALUE FROM
QSYS2.SYSTEM_VALUE_INFO A
LEFT EXCEPTION JOIN SESSION.Remote_System_Values B
ON A.SYSTEM_VALUE_NAME = B.SYSTEM_VALUE_NAME AND
A.CURRENT_NUMERIC_VALUE IS NOT DISTINCT FROM B.CURRENT_NUMERIC_VALUE AND
A.CURRENT_CHARACTER_VALUE IS NOT DISTINCT FROM B.CURRENT_CHARACTER_VALUE
Use a query to
UNION ALL find the
SELECT 'X1423P2' AS "System Name", SYSVAL
B.SYSTEM_VALUE_NAME,B.CURRENT_NUMERIC_VALUE,B.CURRENT_CHARACTER_VALUE FROM
QSYS2.SYSTEM_VALUE_INFO A
differences
between the
RIGHT EXCEPTION JOIN SESSION.Remote_System_Values B
two systems
ON A.SYSTEM_VALUE_NAME = B.SYSTEM_VALUE_NAME AND
A.CURRENT_NUMERIC_VALUE IS NOT DISTINCT FROM B.CURRENT_NUMERIC_VALUE AND
A.CURRENT_CHARACTER_VALUE IS NOT DISTINCT FROM B.CURRENT_CHARACTER_VALUE
ORDER BY SYSTEM_VALUE_NAME;
32 © 2015 IBM Corporation SQL for the System Admin
QSYS2.SYSTEM_VALUE_INFO – view

Example exception join output using SYSTEM_VALUE_INFO.

33 © 2015 IBM Corporation SQL for the System Admin


SQL catalogs  Command Services

Librarian Services

34 © 2015 IBM Corporation SQL for the System Admin


QSYS2.LIBRARY_LIST_INFO – view

• With direct access to the library list, SQL users can tap into the library list detail to:
• Programmatically review the environment
• Know when the library list needs to be adjusted
• Derive information about the libraries
 IASP Number
 Schema vs Library name mapping
 User vs System vs Product libraries
 Above all else, order of libraries searched for unqualified objects

-- Programmatically review the library list detail for this connection


SELECT * FROM QSYS2.LIBRARY_LIST_INFO;

35 © 2015 IBM Corporation SQL for the System Admin


QSYS2.SYSCATALOGS – view

• The SYSCATALOGS catalog mirrors the Relational Database Entries


(WRKRDBDIRE)
• The catalog returns status information for Independent ASPs (iASPs)
• CATALOG_STATUS values
 AVAILABLE – available for use
 ACTIVE – In the process of becoming available
 VARYON – About to begin the vary on process
 VARYOFF – Offline, not useable

-- Query the existence & state of the local database and iASPs
SELECT CATALOG_NAME, CATALOG_STATUS, CATALOG_ASPNUM FROM
QSYS2.SYSCATALOGS WHERE CATALOG_TYPE = 'LOCAL‘;

36 © 2015 IBM Corporation SQL for the System Admin


SQL catalogs  Command Services

Message Handling Services

37 © 2015 IBM Corporation SQL for the System Admin


QSYS2.JOBLOG_INFO – UDTF
• Job logs contain essential information.
• To understand a failure, job log messages are reviewed
• To understand which CL commands were issued, REQUEST messages in
the job log are reviewed
• Even though trace and failure collection instrumentation exists, job logs are
frequently requested by IBM Service
• The JOBLOG_INFO() UDTF provides a new service for application developers
and system managers
• A single parameter indicates the target job.
• ‘*’ can be used to indicate use the current job as the target.

-- Find the most recently executed command in a target job


SELECT MESSAGE_TEXT FROM
TABLE(QSYS2.JOBLOG_INFO('706721/SCOTTF/QPADEV0006')) A
WHERE A.MESSAGE_TYPE = 'REQUEST'
ORDER BY ORDINAL_POSITION DESC
FETCH FIRST 1 ROW ONLY;

38 © 2015 IBM Corporation SQL for the System Admin


QSYS2.JOBLOG_INFO – UDTF
-- Automatic consumption of job log in an application
CREATE OR REPLACE PROCEDURE TOYSTORE.UPDATE_SALES
(IN P_NEW_SALES INTEGER, IN P_SALES_PERSON VARCHAR(100),
IN P_SALES_DATE DATE)
DYNAMIC RESULT SETS 1
LANGUAGE SQL MODIFIES SQL DATA SET OPTION COMMIT = *CHG
BEGIN
DECLARE C_RESULT_SET1 CURSOR WITH RETURN TO CALLER FOR SELECT MESSAGE_ID, MESSAGE_TEXT,
MESSAGE_TYPE FROM SESSION.My_Joblog;

Mainline: BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
DECLARE GLOBAL TEMPORARY TABLE My_Joblog AS
(SELECT * FROM TABLE(QSYS2.JOBLOG_INFO('*')) A)
WITH DATA WITH REPLACE;
OPEN C_RESULT_SET1;
END;

UPDATE TOYSTORE.SALES
SET SALES = SALES + P_NEW_SALES
WHERE SALES_PERSON = P_SALES_PERSON
AND SALES_DATE = P_SALES_DATE;
END Mainline;
END ;

CALL TOYSTORE.UPDATE_SALES(3, 'LUCCHESSI', '1995-12-31');


39 © 2015 IBM Corporation SQL for the System Admin
QSYS2.JOBLOG_INFO – UDTF
-- Saving job log detail to a permanent table
CREATE TABLE APPLIB.Joblog_Detail AS (SELECT QSYS2.JOB_NAME, A.* FROM
TABLE(QSYS2.JOBLOG_INFO('*')) A) WITH NO DATA;

CREATE OR REPLACE PROCEDURE TOYSTORE.UPDATE_SALES


(IN P_NEW_SALES INTEGER, IN P_SALES_PERSON VARCHAR(100),
IN P_SALES_DATE CHAR(10))
LANGUAGE SQL MODIFIES SQL DATA

Mainline: BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
INSERT INTO APPLIB.Joblog_Detail
SELECT QSYS2.JOB_NAME, A.* FROM TABLE(QSYS2.JOBLOG_INFO('*')) A
ORDER BY ORDINAL_POSITION DESC
FETCH FIRST 5 ROWS ONLY;

UPDATE TOYSTORE.SALES
SET SALES = SALES + P_NEW_SALES
WHERE SALES_PERSON = P_SALES_PERSON
AND SALES_DATE = P_SALES_DATE;
END Mainline;
40 © 2015 IBM Corporation SQL for the System Admin
QSYS2.JOBLOG_INFO – UDTF
Automatic consumption of job log in an application
call TOYSTORE.UPDATE_SALES(5, 'Frank Salesguy', '2014-1011');

SELECT A.JOB_NAME, MESSAGE_ID, MESSAGE_TEXT,MESSAGE_TOKENS,A.*


from APPLIB.Joblog_Detail A ORDER BY MESSAGE_TIMESTAMP ASC;

41 © 2015 IBM Corporation SQL for the System Admin


QSYS2.REPLY_LIST_INFO – view

• One reply list handles system wide automatic response to messages


• Now, SQL can be used to:
 Compare (exception join) the configuration of two machines
 Determine whether a specific sequence number is already in use
 Confirm whether setup is complete
• REPLY_LIST_INFO matches the Work Reply List Entry (WRKRPYLE) command
behavior of allowing *PUBLIC users to view the reply list information

-- Review reply list detail for all messages which begin with ‘CPA’
SELECT * FROM QSYS2.REPLY_LIST_INFO
WHERE message_ID like 'CPA%‘;

42 © 2015 IBM Corporation SQL for the System Admin


SQL catalogs  Security Services

Security Services

43 © 2015 IBM Corporation SQL for the System Admin


QSYS2.GROUP_PROFILE_ENTRIES – view

Use SQL to understand:


• What Group Profiles exist
• Which User Profiles belong to specific Group Profiles
• The text associated with the profile
Handles both:
Group profile . . . . . . . . . GRPPRF
Supplemental groups . . SUPGRPPRF

-- Examine all groups and the group members


SELECT * from qsys2.group_profile_entries;

44 © 2015 IBM Corporation SQL for the System Admin


SYSIBM.AUTHORIZATIONS – view

The AUTHORIZATIONS catalog has been extended to include a new column,


which differentiates users from groups.

The AUTHORIZATIONS view is a DB2 family compatible catalog which contains


one row for every authorization ID.

45 © 2015 IBM Corporation SQL for the System Admin


QSYS2.USER_INFO – view

• Built upon the data returned by the Retrieve User Information (QSYRUSRI) API.
• Users see the data for any *USRPRF to which they have *READ authority
• Setup details, authorizations, and more… easy access to deep details

-- Which users are having trouble signing on?


SELECT * FROM QSYS2.USER_INFO
WHERE SIGN_ON_ATTEMPTS_NOT_VALID > 0;

46 © 2015 IBM Corporation SQL for the System Admin


USER_INFO & GROUP_PROFILE_ENTRIES

• Leverage multiple services to answer more interesting questions

--
-- Which users have *ALLOBJ authority either directly
-- or via a Group or Supplemental profile?
--
SELECT AUTHORIZATION_NAME, STATUS, NO_PASSWORD_INDICATOR,
PREVIOUS_SIGNON,
TEXT_DESCRIPTION
FROM QSYS2.USER_INFO
WHERE SPECIAL_AUTHORITIES LIKE '%*ALLOBJ%'
OR AUTHORIZATION_NAME IN (
SELECT USER_PROFILE_NAME
FROM QSYS2.GROUP_PROFILE_ENTRIES
WHERE GROUP_PROFILE_NAME IN (
SELECT AUTHORIZATION_NAME
FROM QSYS2.USER_INFO
WHERE SPECIAL_AUTHORITIES like '%*ALLOBJ%'
)
)
ORDER BY AUTHORIZATION_NAME;
47 © 2015 IBM Corporation SQL for the System Admin
USER_INFO & GROUP_PROFILE_ENTRIES

• Query results…

48 © 2015 IBM Corporation SQL for the System Admin


QSYS2.USER_INFO – view

• Extended to include columns that are available to users of the QSYRUSRI() API.

-- Which users are at risk of becoming disabled due to lack of use?


SELECT * FROM QSYS2.USER_INFO
WHERE STATUS = '*ENABLED' AND LAST_USED_TIMESTAMP IS NOT NULL
ORDER BY LAST_USED_TIMESTAMP ASC
FETCH FIRST 20 ROWS ONLY;

New Columns

49 © 2015 IBM Corporation SQL for the System Admin


QSYS2.FUNCTION_INFO – view

• Built upon the data returned by the Retrieve Function Information


(QSYRTVFI, QsyRetrieveFunctionInformation) API
• Any user can examine the function usage identifiers.
• Only users with *SECADM user special authority can examine the function usage
configuration details returned via the QSYS2.FUNCTION_INFO catalog.
• Each row describes the function usage defined on the machine.
Example:
-- Which function usage IDs exist and what is the default configuration?
SELECT * FROM QSYS2.FUNCTION_INFO ORDER BY FUNCTION_ID;

50 © 2015 IBM Corporation SQL for the System Admin


QSYS2.FUNCTION_USAGE – view

• The detail returned corresponds to the data returned by


the Retrieve Function Usage Information
(QSYRTFUI, QsyRetrieveFunctionUsageInfo) API.
• Only users with *SECADM user special authority can examine the function usage
configuration details returned with this view. Users without *SECADM authority who attempt
to reference this view will get SQLCODE -443.
• Each row corresponds with users or groups that have function usage settings
Example:
-- What function usage has been granted or revoked?
SELECT * FROM QSYS2.FUNCTION_USAGE ORDER BY FUNCTION_ID, USER_NAME;

51 © 2015 IBM Corporation SQL for the System Admin


SQL catalogs  Storage Services

Storage Services

52 © 2015 IBM Corporation SQL for the System Admin


QSYS2.USER_STORAGE – view

• Built upon the data returned by the Retrieve User Information (QSYRUSRI) API.
• Users see the data for any *USRPRF to which they have *READ authority
• User storage is broken down by SYSBAS and iASPs

-- How much storage has user SCOTTF consumed?


SELECT * FROM QSYS2.USER_STORAGE
WHERE USER_NAME = ‘SCOTTF’;

53 © 2015 IBM Corporation SQL for the System Admin


QSYS2.USER_STORAGE – view

-- Review the top 10 storage consumers


SELECT A.AUTHORIZATION_NAME, SUM(A.STORAGE_USED) AS
TOTAL_STORAGE_USED, B.TEXT_DESCRIPTION, B.ACCOUNTING_CODE,
B.MAXIMUM_ALLOWED_STORAGE
FROM QSYS2.USER_STORAGE A
INNER JOIN QSYS2.USER_INFO B ON B.USER_NAME = A.AUTHORIZATION_NAME
GROUP BY A.AUTHORIZATION_NAME, B.TEXT_DESCRIPTION,
B.ACCOUNTING_CODE, B.MAXIMUM_ALLOWED_STORAGE
ORDER BY TOTAL_STORAGE_USED DESC FETCH FIRST 10 ROWS ONLY;

54 © 2015 IBM Corporation SQL for the System Admin


QSYS2.SYSDISKSTAT – view
The SYSDISKSTAT catalog can be used to quickly and easily understand the DISK information
using SQL.
Examples:
-- Query information for all SSD units
SELECT * FROM QSYS2.SYSDISKSTAT WHERE UNIT_TYPE = 1;
-- Query information for all DISKs, order by percentage used
SELECT PERCENT_USED, A.* FROM QSYS2.SYSDISKSTAT A
ORDER BY PERCENT_USED DESC;

55 © 2015 IBM Corporation SQL for the System Admin


QSYS2.SYSTMPSTG – view
Improved
• Observe System-wide Temporary storage consumption System Management
via a new DB2 for i Service: QSYS2.SYSTMPSTG
with DB2 for i
• Read all about it in IBM Knowledge Center:
www.ibm.com/support/knowledgecenter/ssw_ibm_i_72/rzajq/rzajqviewsystmpstg.htm

-- Which active jobs are the top consumers of temporary storage?


SELECT bucket_current_size, bucket_peak_size,
rtrim(job_number) concat '/' concat rtrim(job_user_name) concat '/'
concat rtrim(job_name) as q_job_name
FROM QSYS2.SYSTMPSTG
WHERE job_status = '*ACTIVE'
ORDER BY
bucket_current_size desc;

56 © 2015 IBM Corporation SQL for the System Admin


QSYS2.SYSTMPSTG – view
Improved
• Combine services to extract more detail System Management
-- Which active database server connections
with DB2 for i
-- are consuming the most temporary storage
WITH TOP_TMP_STG (bucket_current_size, q_job_name) AS (
SELECT bucket_current_size, rtrim(job_number) concat '/' concat
rtrim(job_user_name) concat '/' concat rtrim(job_name) as
q_job_name
FROM QSYS2.SYSTMPSTG
WHERE job_status = '*ACTIVE' AND
JOB_NAME IN ('QZDASOINIT', 'QZDASSINIT', 'QRWTSRVR', 'QSQSRVR')
ORDER BY bucket_current_size desc fetch first 10 rows only
) SELECT bucket_current_size, q_job_name, V_SQL_STATEMENT_TEXT, B.*
FROM TOP_TMP_STG, TABLE(QSYS2.GET_JOB_INFO(q_job_name)) B;

57 © 2015 IBM Corporation SQL for the System Admin


SQL catalogs  Command Services

Command Services

58 © 2015 IBM Corporation SQL for the System Admin


QSYS2.QCMDEXC – Procedure
The QCMDEXC procedure can be used within SQL applications to easily execute CL
Commands.
Examples:
• DECLARE V_CPYLIB_COMMAND VARCHAR(500);
DECLARE V_CPYLIB_LEN DECIMAL(15, 5);
SET V_CPYLIB_COMMAND =
'CPYLIB FROMLIB(' CONCAT RTRIM(V_LIBRARY) CONCAT
') TOLIB(' CONCAT RTRIM(V_NEW_LIBRARY) CONCAT ')
DATA(*NO)‘;
SET V_CPYLIB_LEN =
CHARACTER_LENGTH(V_CPYLIB_COMMAND);
CALL QSYS2.QCMDEXC(V_CPYLIB_COMMAND, V_CPYLIB_LEN);
• CALL QSYS2.QCMDEXC('ADDLIBLE PRODLIB2',17);

• Length argument no longer required:


CALL QSYS2.QCMDEXC('ADDLIBLE PRODLIB2');

59 © 2015 IBM Corporation SQL for the System Admin


DB2 for i built-in Global Variables

Built-in Global Variables

60 © 2015 IBM Corporation SQL for the System Admin


DB2 for i Built-in Global Variables
• The qualified job name of the current connection is easily accessed
• When SQL Server Mode is used, the job name of the application instance
which owns the connection is accessed through SERVER_MODE_JOB_NAME
• Use these variables to deploy advanced logic in triggers, RCAC rules, and
more
Variable name Schema Data Type Size
New with
JOB_NAME QSYS2 VARCHAR 28
IBM i 7.2
SF99702 SERVER_MODE_JOB_NAME QSYS2 VARCHAR 28
Level 3 CLIENT_IPADDR SYSIBM VARCHAR 128
CLIENT_HOST SYSIBM VARCHAR 255
CLIENT_PORT SYSIBM INTEGER -
Available PACKAGE_NAME SYSIBM VARCHAR 128
with PACKAGE_SCHEMA SYSIBM VARCHAR 128
base
PACKAGE_VERSION SYSIBM VARCHAR 64
IBM i 7.2
ROUTINE_SCHEMA SYSIBM VARCHAR 128
ROUTINE_SPECIFIC_NAME SYSIBM VARCHAR 128

61
ROUTINE_TYPE SYSIBM CHAR 1
SQL for the System Admin
© 2015 IBM Corporation
Built-in Global Variables – Client information
• Two ways to extract the detail
• Global variables fit nicely into view definitions &
RCAC masks/permissions
SELECT SYSIBM.client_host AS CLIENT_HOST,
SYSIBM.client_ipaddr AS CLIENT_IP,
SYSIBM.client_port AS CLIENT_PORT
FROM LP92UT27.SYSIBM.SYSDUMMY1;

SELECT * FROM LP92UT27.QSYS2.TCPIP_INFO;

62 © 2015 IBM Corporation SQL for the System Admin


Built-in Global Variables – Routine information
create procedure scottf.show_GV_values(
rtn_schema_p out varchar(128), Variables reflect the currently
rtn_specific_name_p out varchar(128), executing routine
rtn_type_p out char(1)) (procedure or function)
language sql
specific scottf.demonstrate_the_new_DB2_for_i_GVs
begin
SET (rtn_schema_p,rtn_specific_name_p,rtn_type_p) =
(SYSIBM.ROUTINE_SCHEMA, SYSIBM.ROUTINE_SPECIFIC_NAME,
SYSIBM.ROUTINE_TYPE);
End;

CALL scottf.show_GV_values(?,?,?);

63 © 2015 IBM Corporation SQL for the System Admin


Built-in Global Variables – Routine information
create or replace function scottf.show_specific_name_function()
returns clob(1K)
language sql Leverage this new insight within
deterministic
code used by procedures and
functions
Begin

RETURN(SYSIBM.ROUTINE_SCHEMA CONCAT '.' CONCAT


SYSIBM.ROUTINE_SPECIFIC_NAME CONCAT
CASE WHEN SYSIBM.ROUTINE_TYPE = 'P' THEN ' PROCEDURE'
WHEN SYSIBM.ROUTINE_TYPE = 'F' THEN ' FUNCTION'
END);
End;
values(scottf.show_specific_name_function());

64 © 2015 IBM Corporation SQL for the System Admin


Built-in Global Variables – DRDA information
• When DRDA is used, the package detail is readily accessible via the new DB2
for i global variables.

• Similar to the routine variables, this can provide easy identification of remote
execution of embedded SQL programs.

SELECT SYSIBM.package_schema AS PACKAGE_SCHEMA,


SYSIBM.package_name AS PACKAGE_NAME,
SYSIBM.package_version AS PACKAGE_VERSION
FROM LP92UT27.SYSIBM.SYSDUMMY1;

65 © 2015 IBM Corporation SQL for the System Admin


SQL catalogs  Landscape view

Landscape

66 © 2015 IBM Corporation SQL for the System Admin


IBM® DB2® for i Catalogs
Catalogs Privileges Routines Statistics
SYSCATALOGS SYSCOLAUTH SYSCOLUMNSTAT
SYSFUNCS
SYSCONTROLS SYSINDEXSTAT
SYSJARCONTENTS
INFORMATION_SCHEMA_CATALOG_NAME SYSCONTROLSDEP SYSMQTSTAT
SYSJAROBJECTS
SYSPACKAGEAUTH SYSPACKAGESTAT
SYSPARMS
Schemas Database Support SYSROUTINEAUTH SYSPACKAGESTMTSTAT
SYSSCHEMAAUTH SYSPROCS
SYSPARTITIONDISK
SYSSCHEMAS SQL_FEATURES SYSROUTINEDEP
SYSSEQUENCEAUTH SYSPARTITIONINDEXES
SQL_LANGUAGES SYSROUTINES
SQLSCHEMAS SYSTABAUTH SYSPARTITIONINDEXDISK
SQL_SIZING SYSUDTAUTH SYSPARTITIONINDEXSTAT
SCHEMATA CHARACTER_SETS SYSVARIABLEAUTH SQLFUNCTIONCOLS
SYSPARTITIONMQTS
SYSXSROBJECTAUTH SQLFUNCTIONS
SYSPARTITIONSTAT
SQLPROCEDURECOLS
Tables Views Indexes SYSPROGRAMSTAT
SQLCOLPRIVILEGES SQLPROCEDURES
SQLTABLEPRIVILEGES SYSPROGRAMSTMTSTAT
SYSCOLUMNS
SYSTABLEINDEXSTAT
SYSCOLUMNS2 AUTHORIZATIONS SYSTABLESTAT
Constraints PARAMETERS
SYSFIELDS ROUTINE_PRIVILEGES
ROUTINES SQLSTATISTICS
SYSINDEXES SYSCHKCST UDT_PRIVILEGES
SYSKEYS USAGE_PRIVILEGES
SYSCST VARIABLE_PRIVILEGES
Miscellaneous Objects
SYSTABLEDEP SYSCSTCOL
SYSTABLES SYSPACKAGE
SYSCSTDEP Triggers XML Schemas
SYSVIEWDEP SYSSEQUENCES
SYSKEYCST
SYSVIEWS SYSTRIGCOL XSRANNOTATIONINFO SYSTYPES
SYSREFCST
SYSTRIGDEP XSROBJECTCOMPONENTS SYSVARIABLEDEP
SQLCOLUMNS SYSTRIGGERS XSROBJECTHIERARCHIES SYSVARIABLES
SQLFOREIGNKEYS
SQLSPECIALCOLUMNS SYSTRIGUPD XSROBJECTS
SQLTABLES SQLPRIMARYKEYS SQLTYPEINFO
SQLUDTS
COLUMNS CHECK_CONSTRAINTS DB2 for i catalog views (QSYS2) USER_DEFINED_TYPES
TABLES REFERENTIAL_CONSTRAINTS ODBC and JDBCTM catalog views (SYSIBM) SEQUENCES
VIEWS TABLE_CONSTRAINTS
ANS and ISO catalog views (QSYS2) http://www.ibm.com/systems/i/software/db2/
Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the United States, other countries, or both.
Other company, product or service names may be trademarks or service marks of others.

67 © 2014 IBM Corporation SQL for the System Admin


IBM® DB2® for i Services
Health Center Procedures Application Services
QSYS2.HEALTH_ACTIVITY
QSYS2.QCMDEXC - PROCEDURE System Health Services
QSYS2.HEALTH_DATABASE_OVERVIEW QSYS2.SYSLIMTBL - TABLE
QSYS2.HEALTH_DESIGN_LIMITS
QSYS2.OVERRIDE_TABLE – PROCEDURE QSYS2.SYSLIMITS – VIEW
QSYS2.HEALTH_ENVIRONMENTAL_LIMITS
QSYS2.HEALTH_SIZE_LIMITS
QSYS2.DELIMIT_NAME – UDF TCP/IP Services
QSYS2.RESET_ENVIRONMENTAL_LIMITS SYSPROC.WLM_SET_CLIENT_INFO – PROCEDURE
QSYS2.TCPIP_INFO – VIEW
Utility Procedures Security Services SYSIBMADM.ENV_SYS_INFO – VIEW
QSYS2.CANCEL_SQL QSYS2.FUNCTION_INFO – VIEW
QSYS2.DUMP_SQL_CURSORS Work Management Services
QSYS2.FUNCTION_USAGE – VIEW
QSYS2.EXTRACT_STATEMENTS QSYS2.GROUP_PROFILE_ENTRIES – VIEW QSYS2.SYSTEM_VALUE_INFO – VIEW
QSYS2.FIND_AND_CANCEL_QSQSRVR_SQL
SYSPROC.SET_COLUMN_ATTRIBUTE - PROCEDURE QSYS2.GET_JOB_INFO – UDTF
QSYS2.FIND_QSQSRVR_JOBS
QSYS2.SQL_CHECK_AUTHORITY - UDF
QSYS2.GENERATE_SQL
QSYS2.RESTART_IDENTITY QSYS2.USER_INFO – VIEW Object Services
SYSTOOLS.CHECK_CST QSYS2.OBJECT_STATISTICS – UDTF
SYSTOOLS.CHECK_SYSROUTINE
PTF Services
QSYS2.PTF_INFO – VIEW Storage Services
Plan Cache Procedures QSYS2.GROUP_PTF_INFO – VIEW QSYS2.SYSDISKSTAT – VIEW
QSYS2.CHANGE_PLAN_CACHE_SIZE SYSTOOLS.GROUP_PTF_CURRENCY -VIEW QSYS2.SYSTMPSTG – VIEW
QSYS2.DUMP_PLAN_CACHE QSYS2.USER_STORAGE – VIEW
QSYS2.DUMP_PLAN_CACHE_PROPERTIES
QSYS2.DUMP_PLAN_CACHE_topN Journal Services
QSYS2.DUMP_SNAP_SHOT_PROPERTIES QSYS2.DISPLAY_JOURNAL – UDTF
QSYS2.END_ALL_PLAN_CACHE_EVENT_MONITORS QSYS2.JOURNAL_INFO – View
QSYS2.END_PLAN_CACHE_EVENT_MONITOR
QSYS2.START_PLAN_CACHE_EVENT_MONITOR (2)
Message Handling Services
QSYS2.JOBLOG_INFO – View
Performance Services QSYS2.REPLY_LIST_INFO – View
SYSTOOLS.ACT_ON_INDEX_ADVICE - PROCEDURE
DB2 for i Services
Librarian Services
SYSTOOLS.HARVEST_INDEX_ADVICE - PROCEDURE
QSYS2.OVERRIDE_QAQQINI - PROCEDURE IBM i Services QSYS2.LIBRARY_LIST_INFO – View
QSYS2.RESET_TABLE_INDEX_STATISTICS - PROCEDURE
QSYS2.SYSIXADV - TABLE http://www.ibm.com/developerworks/ibmi/db2
SYSTOOLS.REMOVE_INDEXES - PROCEDURE
http://www.ibm.com/developerworks/ibmi/techupdates/db2/landscape

68 © 2014 IBM Corporation SQL for the System Admin


Documentation

• With IBM i 7.2, these and other


services are documented within the
“Database Performance and
Optimization” book

• The Technology Updates wiki


includes fact pages for these
services

http://ibm.biz/DB2foriServices

69 © 2015 IBM Corporation SQL for the System Admin


Special notices
This document was developed for IBM offerings in the United States as of the date of publication. IBM may not make these offerings available in
other countries, and the information is subject to change without notice. Consult your local IBM business contact for information on the IBM
offerings available in your area.
Information in this document concerning non-IBM products was obtained from the suppliers of these products or other public sources. Questions
on the capabilities of non-IBM products should be addressed to the suppliers of those products.
IBM may have patents or pending patent applications covering subject matter in this document. The furnishing of this document does not give
you any license to these patents. Send license inquires, in writing, to IBM Director of Licensing, IBM Corporation, New Castle Drive, Armonk, NY
10504-1785 USA.
All statements regarding IBM future direction and intent are subject to change or withdrawal without notice, and represent goals and objectives
only.
The information contained in this document has not been submitted to any formal IBM test and is provided "AS IS" with no warranties or
guarantees either expressed or implied.
All examples cited or described in this document are presented as illustrations of the manner in which some IBM products can be used and the
results that may be achieved. Actual environmental costs and performance characteristics will vary depending on individual client configurations
and conditions.
IBM Global Financing offerings are provided through IBM Credit Corporation in the United States and other IBM subsidiaries and divisions
worldwide to qualified commercial and government clients. Rates are based on a client's credit rating, financing terms, offering type, equipment
type and options, and may vary by country. Other restrictions may apply. Rates and offerings are subject to change, extension or withdrawal
without notice.
IBM is not responsible for printing errors in this document that result in pricing or information inaccuracies.
All prices shown are IBM's United States suggested list prices and are subject to change without notice; reseller prices may vary.
IBM hardware products are manufactured from new parts, or new and serviceable used parts. Regardless, our warranty terms apply.
Any performance data contained in this document was determined in a controlled environment. Actual results may vary significantly and are
dependent on many factors including system hardware configuration and software design and configuration. Some measurements quoted in this
document may have been made on development-level systems. There is no guarantee these measurements will be the same on generally-
available systems. Some measurements quoted in this document may have been estimated through extrapolation. Users of this document
should verify the applicable data for their specific environment.

70 © 2015 IBM Corporation SQL for the System Admin


Special notices (cont.)
IBM, the IBM logo, ibm.com AIX, AIX (logo), AIX 6 (logo), AS/400, BladeCenter, Blue Gene, ClusterProven, DB2, ESCON, i5/OS, i5/OS (logo), IBM Business Partner
(logo), IntelliStation, LoadLeveler, Lotus, Lotus Notes, Notes, Operating System/400, OS/400, PartnerLink, PartnerWorld, PowerPC, pSeries, Rational, RISC
System/6000, RS/6000, THINK, Tivoli, Tivoli (logo), Tivoli Management Environment, WebSphere, xSeries, z/OS, zSeries, AIX 5L, Chiphopper, Chipkill, Cloudscape, DB2
Universal Database, DS4000, DS6000, DS8000, EnergyScale, Enterprise Workload Manager, General Purpose File System, , GPFS, HACMP, HACMP/6000, HASM, IBM
Systems Director Active Energy Manager, iSeries, Micro-Partitioning, POWER, PowerExecutive, PowerVM, PowerVM (logo), PowerHA, Power Architecture, Power
Everywhere, Power Family, POWER Hypervisor, Power Systems, Power Systems (logo), Power Systems Software, Power Systems Software (logo), POWER2,
POWER3, POWER4, POWER4+, POWER5, POWER5+, POWER6, POWER6+, System i, System p, System p5, System Storage, System z, Tivoli Enterprise, TME 10,
Workload Partitions Manager and X-Architecture are trademarks or registered trademarks of International Business Machines Corporation in the United States, other
countries, or both. If these and other IBM trademarked terms are marked on their first occurrence in this information with a trademark symbol (® or ™), these symbols
indicate U.S. registered or common law trademarks owned by IBM at the time this information was published. Such trademarks may also be registered or common law
trademarks in other countries. A current list of IBM trademarks is available on the Web at "Copyright and trademark information" at www.ibm.com/legal/copytrade.shtml

The Power Architecture and Power.org wordmarks and the Power and Power.org logos and related marks are trademarks and service marks licensed by Power.org.
UNIX is a registered trademark of The Open Group in the United States, other countries or both.
Linux is a registered trademark of Linus Torvalds in the United States, other countries or both.
Microsoft, Windows and the Windows logo are registered trademarks of Microsoft Corporation in the United States, other countries or both.
Intel, Itanium, Pentium are registered trademarks and Xeon is a trademark of Intel Corporation or its subsidiaries in the United States, other countries or both.
AMD Opteron is a trademark of Advanced Micro Devices, Inc.
Java and all Java-based trademarks and logos are trademarks of Sun Microsystems, Inc. in the United States, other countries or both.
TPC-C and TPC-H are trademarks of the Transaction Performance Processing Council (TPPC).
SPECint, SPECfp, SPECjbb, SPECweb, SPECjAppServer, SPEC OMP, SPECviewperf, SPECapc, SPEChpc, SPECjvm, SPECmail, SPECimap and SPECsfs are
trademarks of the Standard Performance Evaluation Corp (SPEC).
NetBench is a registered trademark of Ziff Davis Media in the United States, other countries or both.
AltiVec is a trademark of Freescale Semiconductor, Inc.
Cell Broadband Engine is a trademark of Sony Computer Entertainment Inc.
InfiniBand, InfiniBand Trade Association and the InfiniBand design marks are trademarks and/or service marks of the InfiniBand Trade Association.
Other company, product and service names may be trademarks or service marks of others.

71 © 2015 IBM Corporation SQL for the System Admin

You might also like