Hot news

Why Oracle DB?

Oracle is the most suitable DB for storing data in high- security mode, arranging BigData , implementing any idea in many applications . ...

Showing posts with label SQL. Show all posts
Showing posts with label SQL. Show all posts

2020-02-28

SQL structure

В этой статье собраны и структурированы минимальные основы SQL Oracle из обширной документации базы данных Oracle 12c. Для тех, кто начинает изучение базы, эта информация поможет обрисовать общую картину. Для разработчиков и тестировщиков базы данных эти таблицы служат удобными помощниками в повседневной работе.
Расшифровки языковых аббревиатур в DB Oracle
SQL Structured Query Language
DDL Data Definition Language (DDL) statements manage schema objects in the database. These statements create new, drop old, and establish schema objects. They also control access to schema objects.
DML Data Manipulation Language (DML) statements can change data in database tables. For example, DML statements insert new rows into a table, update column values in existing rows, delete rows from a table, lock a table in the database, and explain the execution plan for a SQL statement.
TCL Transaction control language
PL Procedural Language
Структуризация
SQL
Static PL/SQL DDL Dynamic PL/SQL SQL*Plus
query DML TCL manage control native DBMS_SQL package
SELECT DELETE COMMIT ALTER ADMINISTER CLOSE DBMS_SQL.RETURN_RESULT Procedure @
EXPLAIN ROLLBACK CREATE ANALYZE EXECUTE IMMEDIATE DBMS_SQL.GET_NEXT_RESULT Procedure @@
INSERT SAVEPOINT DROP ASSOCIATE FETCH DBMS_SQL.TO_REFCURSOR Function /
LOCK TABLE SET TRANSACTION FLASHBACK AUDIT OPEN FOR DBMS_SQL.TO_CURSOR_NUMBER Function ACCEPT, APPEND, ARCHIVE, ATTRIBUTE
MERGE GRANT CALL BREAK, BTITLE
UPDATE PURGE COMMENT CHANGE, CLEAR, COLUMN, COMPUTE, CONNECT, COPY
RENAME DISASSOCIATE DEFINE, DEL, DESCRIBE, DISCONNECT
REVOKE NOAUDIT EDIT, EXECUTE, EXIT
TRUNCATE SET (constraint, role) GET
HELP, HOST
INPUT
LIST
PASSWORD, PAUSE, PRINT, PROMPT
QUIT
RECOVER, REMARK, REPFOOTER, REPHEADER, RUN
SAVE, SET, SHOW, SHUTDOWN, SPOOL, START, STARTUP, STORE
TIMING, TTITLE
UNDEFINE
VARIABLE
WHENEVER
XQUERY

Нижеследующие списки касаются PL (Procedural Language)
Stored PL/SQL Units
Anonymous Block - часть хранимых подпрограмм, самостоятельный блок в скрипте или теле джоба, триггера
FUNCTION
LIBRARY
PACKAGE
PACKAGE BODY
PROCEDURE
TRIGGER
TYPE
TYPE BODY

PL/SQL Data Types
SQL BOOLEAN INTEGER REF CURSOR User-Defined Subtypes Predefined
BINARY_FLOAT SIMPLE_INTEGER Unconstrained BFILE
BINARY_DOUBLE PLS_INTEGER Constrained BLOB
CHAR BINARY_INTEGER with Base Types BOOLEAN
VARCHAR2 CHAR
LONG CLOB
LONG RAW DATE
ROWID NUMBER
UROWID

PL/SQL Collections and Records Collection Methods
Associative Arrays Collection Types Multidimensional Collections Nested Tables Varrays (Variable-Size Arrays) Record COUNT
%ROWTYPE Attribute DELETE
Constants EXISTS
Types EXTEND
Variables FIRST
LAST
LIMIT
NEXT
PRIOR
TRIM

PL/SQL Language Elements
Statement Pragma Constuction Declaration Attributes Others
Assignment AUTONOMOUS_TRANSACTION Block Collection Variable Implicit Cursor Collection Method Invocation
Basic LOOP EXCEPTION_INIT Comment Constant Named Cursor RETURNING INTO Clause
CASE INLINE Exception Handler Cursor Variable %ROWTYPE SQLCODE Function
CLOSE RESTRICT_REFERENCES Expression Exception %TYPE SQLERRM Function
CONTINUE SERIALLY_REUSABLE Explicit Cursor
Cursor FOR LOOP UDF Formal Parameter
DELETE Function
EXECUTE IMMEDIATE Procedure
EXIT Record Variable
FETCH Scalar Variable
FOR LOOP
FORALL
GOTO
IF
INSERT
NULL
OPEN
OPEN FOR
PIPE ROW
RAISE
RETURN
SELECT INTO
UPDATE
WHILE LOOP

PL/SQL Control Statements
Conditional Selection LOOP Sequential Control
IF THEN LOOP GOTO
IF THEN ELSE EXIT NULL
IF THEN ELSIF EXIT WHEN
Simple CASE CONTINUE
Searched CASE CONTINUE WHEN
FOR LOOP
WHILE LOOP

SQL Statements for Stored PL/SQL Units
Изменение свойств* Создание Удаление
ALTER FUNCTION CREATE FUNCTION DROP FUNCTION
ALTER LIBRARY CREATE LIBRARY DROP LIBRARY
ALTER PACKAGE CREATE PACKAGE DROP PACKAGE
CREATE PACKAGE BODY DROP PACKAGE BODY**
ALTER PROCEDURE CREATE PROCEDURE DROP PROCEDURE
ALTER TRIGGER CREATE TRIGGER DROP TRIGGER
ALTER TYPE CREATE TYPE DROP TYPE
CREATE TYPE BODY DROP TYPE BODY
* - вместо внесения изменений через ALTER-команду можно пересоздать объект командой CREATE OR REPLACE. При этом объект сохранит статус, например, включенность триггера. ** - в документации Oracle пропущена команда, но удалить тело пакета с сохранением его спецификации позволительно

PL/SQL Reserved Words
ALL, ALTER, AND, ANY, AS, ASC, AT
BEGIN, BETWEEN, BY
CASE, CHECK, CLUSTERS, CLUSTER, COLAUTH, COLUMNS, COMPRESS, CONNECT, CRASH, CREATE, CURSOR
DECLARE, DEFAULT, DESC, DISTINCT, DROP
ELSE, END, EXCEPTION, EXCLUSIVE
FETCH, FOR, FROM, FUNCTION
GOTO, GRANT, GROUP
HAVING
IDENTIFIED, IF, IN, INDEX, INDEXES, INSERT, INTERSECT, INTO, IS
LIKE, LOCK
MINUS, MODE
NOCOMPRESS, NOT, NOWAIT, NULL
OF, ON, OPTION, OR, ORDER, OVERLAPS
PROCEDURE, PUBLIC
RESOURCE, REVOKE
SELECT, SHARE, SIZE, SQL, START, SUBTYPE
TABAUTH, TABLE, THEN, TO, TYPE
UNION, UNIQUE, UPDATE
VALUES, VIEW, VIEWS
WHEN, WHERE, WITH

PL/SQL Keywords
A, ADD, ACCESSIBLE, AGENT, AGGREGATE, ARRAY, ATTRIBUTE, AUTHID, AVG
BFILE_BASE, BINARY, BLOB_BASE, BLOCK, BODY, BOTH, BOUND, BULK, BYTE
C, CALL, CALLING, CASCADE, CHAR, CHAR_BASE, CHARACTER, CHARSET, CHARSETFORM, CHARSETID, CLOB_BASE, CLONE, CLOSE, COLLECT, COMMENT, COMMIT, COMMITTED, COMPILED, CONSTANT, CONSTRUCTOR, CONTEXT, CONTINUE, CONVERT, COUNT, CREDENTIAL, CURRENT, CUSTOMDATUM
DANGLING, DATA, DATE, DATE_BASE, DAY, DEFINE, DELETE, DETERMINISTIC, DIRECTORY, DOUBLE, DURATION
ELEMENT, ELSIF, EMPTY, ESCAPE, EXCEPT, EXCEPTIONS, EXECUTE, EXISTS, EXIT, EXTERNAL
FINAL, FIRST, FIXED, FLOAT, FORALL, FORCE
GENERAL
HASH, HEAP, HIDDEN, HOUR
IMMEDIATE, INCLUDING, INDICATOR, INDICES, INFINITE, INSTANTIABLE, INT, INTERFACE, INTERVAL, INVALIDATE, ISOLATION
JAVA
LANGUAGE, LARGE, LEADING, LENGTH, LEVEL, LIBRARY, LIKE2, LIKE4, LIKEC, LIMIT, LIMITED, LOCAL, LONG, LOOP
MAP, MAX, MAXLEN, MEMBER, MERGE, MIN, MINUTE, MOD, MODIFY, MONTH, MULTISET
NAME, NAN, NATIONAL, NATIVE, NCHAR, NEW, NOCOPY, NUMBER_BASE
OBJECT, OCICOLL, OCIDATE, OCIDATETIME, OCIDURATION, OCIINTERVAL, OCILOBLOCATOR, OCINUMBER, OCIRAW, OCIREF, OCIREFCURSOR, OCIROWID, OCISTRING, OCITYPE, OLD, ONLY, OPAQUE, OPEN, OPERATOR, ORACLE, ORADATA, ORGANIZATION, ORLANY, ORLVARY, OTHERS, OUT, OVERRIDING
PACKAGE, PARALLEL_ENABLE, PARAMETER, PARAMETERS, PARENT, PARTITION, PASCAL, PIPE, PIPELINED, PLUGGABLE, PRAGMA, PRECISION, PRIOR, PRIVATE
RAISE, RANGE, RAW, READ, RECORD, REF, REFERENCE, RELIES_ON, REM, REMAINDER, RENAME, RESULT, RESULT_CACHE, RETURN, RETURNING, REVERSE, ROLLBACK, ROW
SAMPLE, SAVE, SAVEPOINT, SB1, SB2, SB4, SECOND, SEGMENT, SELF, SEPARATE, SEQUENCE, SERIALIZABLE, SET, SHORT, SIZE_T, SOME, SPARSE, SQLCODE, SQLDATA, SQLNAME, SQLSTATE, STANDARD, STATIC, STDDEV, STORED, STRING, STRUCT, STYLE, SUBMULTISET, SUBPARTITION, SUBSTITUTABLE, SUM, SYNONYM
TDO, THE, TIME, TIMESTAMP, TIMEZONE_ABBR, TIMEZONE_HOUR, TIMEZONE_MINUTE, TIMEZONE_REGION, TRAILING, TRANSACTION, TRANSACTIONAL, TRUSTED
UB1, UB2, UB4, UNDER, UNPLUG, UNSIGNED, UNTRUSTED, USE, USING
VALIST, VALUE, VARIABLE, VARIANCE, VARRAY, VARYING, VOID
WHILE, WORK, WRAPPED, WRITE
YEAR
ZONE

2018-06-12

Automation of SD work

Work in SQLDetective (SD) may be automated not only by Macros Feature that has problems:
- actions are saved by cursor position and after changing the window position the macro execution will be incorrect;
- actions may be saved by hot-key but Icon Dictionary allows to change the hot-keys all over application, so the macro execution will be incorrect.
Workspace in SD has many useful settings that can automate your work. Unfortunately, there is no topics in Online Help for Preferences, but not all of them are intuitively named.
Here is a list of options that automate the SD tools using. They are grouped by SD users: all types, DB admin, data user, PL/SQL and DB developer.
ALL TYPES of SD user
1. Any user may start SD by command line with connection to DB (for example, "C:\Program Files\SQLDetective\sd.exe CONNECT=scott/tiger@ora101.world") but as the values of CMD line are formatted to lowercase on executing then the auto-connect will fail for initcaps names of DB, login or password. Also, it's not good to store the un-ciphered username and password in bat-file for SD auto-start.
2. "Preferences / General / File Handling"
• "Associate with SQLDetective" (file extensions)
For setting and using these options you should start SD as Windows OS Admin. Otherwise, each SD start will disturb you by many unnecessary warning (error) messages about each selected file extension. Workaround: set the admin run to "c:\Program Files\SQLDetective 4.7\SD.exe" file in Windows OS. Help of these options using is the fast start of SD with auto-opening Stored Program Editor for procedures, functions, packages and object types and SQL Editor opening for all other objects including triggers, jobs, other stored objects or data. Note: store the object DDL in text files with type extension (unfortunately, only SQL Editor opens for them instead of referenced Object Wizard) or other scripts (pl/sql, dml, ddl) in sql-files.
3. "Preferences / General / Workspace"
• "Remember open object"
• "Remember open windows" = "Auto" or "Save / [WindowName] / AutoOpen + Size + Position + State"
These workspace options allow to auto-open any window on application session start and on new DB connection. Note: windows that depended on DB session (object wizards) will open only for linked connect, windows with ability to change the DB session or not linked with DB session (SQL Editor, Stored Program Editor, SmartDataset, all DBA tools, Output Window and others) will open on each DB connect. The most useful settings for fast work are the following: "Remember open objects"=ON, "Prompt on open objects"=OFF, "Confirm save and restore"=OFF, "Remember open windows"=AUTO, "Save"=AutoOpen(All OFF)+Size(All ON)+Position(All ON)+State(All ON).
4. "Preferences / Code Editors / SQL Editor / Editor and Tab Handling"
• "Open file in a new page"
• "Remember SQL statements"
• "Editor and Data Tab Synchronization" = sync activation, opening, renaming, closing
Several options in Preferences and the "Smart Output" option in SQL Editor allow to use the editor and output tabs more logically. Combine the options as you prefer.
5. "Preferences / General / Session"
• "Auto commit after each statement" (dataset, sql editor, object wizard,..) Note: there is a standalone option for dropping a job - "Preferences / Object Operations Handling / Jobs / Enable the commit check box in job dropping prompt window"
• "On disconnect" = "Commit"/"Rollback"/"Prompt"
• "Keep connection alive", "Ping the database every [X] seconds"
In order to forget the "F10" hot-key (COMMIT command execution) you may set the session options. Also they help to keep the remote connection alive always.
6. Any automated work must be logged. It may be done by "View / Output Window" opened from main menu. Any application actions (open/close window, hot-key pressing) are logged but the result should be saved manually. Some application errors are stored in the "%AppData%\Roaming\SQLDetective\SD.log" file.
7. Icon Dictionary allows to set toolbars and hot-keys for quick opening the linked tools. After that you may create and use macros more correctly.
DATA user
1. "Preferences / General / Object Navigator"
• "Remember open scene"
• "Quick navigation element count" = 10 or more
About Scene feature you may read in the "Object Navigator – SceneSelector" and "Object Navigator – Overview" topics of Online Help. Scenes allow to auto-open all necessity tabs in Object Navigator. The number of last opened folders in Object Navigator helps to open or locate objects faster.
2. "Preferences / Dataset Editors"
• "Commit on post"
• "Confirm view data that led to the error"
• "Clicking on the column title sorts data on the" = "Local"/"Server"
• "Autofit columns to" = "Data"/"Title"/"Data and title"
• "Print dataset query and session in report title" instead of Data Exporting
3. "Preferences / Code Editors / SQL Editor / Data Output"
• "Open a new dataset for each query executed in a bundle"
• "Keep column settings"
4. "Preferences / Dataset Editors / Smart Dataset"
• "Open separate window for each object"
5. "Preferences / Dataset Editors / List of Values"
• "Auto locate referenced data"
On working with datasets in SmartDataset or Data Output tab in SQL Editor, or Dataset page in Table, View and Mat.View wizards, or data grids in Object Navigator the listed options automatically show, edit and print data in personal mode.
6. "Preferences / Query Builder"
• "Auto link enabled"
• "Autosave property enabled"
• "Format SQL"
7. "Preferences / General / Version Control System" = "Built-in"
• "Open last used project at start up"
8. "Preferences / Repository"
• "Activate repository on startup"
Query Builder (main menu "Tools / Query Builder") generates a DML statement of any complexity level and join, it allows to name and order columns in user's mode. In a couple with Dataset Manager and Version Control System you may work with data in SmartDataset as in own application in single-record or grid mode. Do the following to create such helpful windows:
a) generate a select statement with joined tables or views by Query Builder;
b) set columns order and local names in Query Builder;
c) export the generated selection into SmartDataset;
d) add filter and sort conditions by Query Builder Editor, set columns width and visibility in SmartDataset and its Dataset Manager ("Filters" and "Columns" tabs);
e) create and open a Built-In Project of SD VCS (main menu "Repository / Install" + "Project / Create New Project" + "Project / Open Project");
f) save the SmartDataset with user's selection into VCS Project (popup menu "Dataset / Save to Project" of SmartDataset).
Next SD start with DB connect (or DB reconnect) will auto-open the SmartDataset with your select statement in the same mode with all settings when SD was closed.
PL/SQL, DB DEVELOPER
1. "Preferences / Code Editors / General"
• Save changes to file when closing window" = "Auto"/"Prompt"
• "Ctrl+Click on Synonyms Navigates to.." = "Synonym"/"Object"
2. "Preferences / Code Editors / Color"
• "Color schemas" = "SD"/"TOAD"/"SQL Navigator"/"PL/SQL Developer"
• Selected fonts are applied only on typing the text. Note: fonts may be changed after formatting by "Code Formatter" feature (main menu "Edit / Format / formatter Options")
3. "Preferences / Code Editors / Stored Program Editor"
• "Compile an invalid stored program after opening"
• "Open Body(Spec) when Spec(Body) opens"
• "Save changes to DB when closing window" = "Auto"/"Prompt"
• "Combine Spec and Body to a single file when saving" = "Auto"/"Prompt"
4. "Preferences / Code Editors / Stored Program Editor / Code Explorer"
• "Enabled"
• "Autonavigate"
5. "Preferences / Code Editors / SQL Editor"
• "Allow only one SQL Editor window"
• "Save sql statement before execute"
• "Skip to the next statement after execution"
• "Create run command for a script file" = "Prompt"/"Always"/"None"
6. "Preferences / Code Editors / SQL Editor / SQL Output"
• A list of options to exclude some PL/SQL commands from executing scripts: SET ECHO OFF, CLEAR SCREEN and so on. Unfortunately, not all option names are intuitive and Online Help does not have any description, so ask CSS TechSupport to explain them more detailed.
7. "Preferences / Code Editors / SQL Editor / SQL Execution History"
• "Remember SQL History List"
• "Ignore non-SQL statements" option works separately from " Preferences / Code Editors / SQL Editor / Save valid sql statements only"
• "Double click on SQL" = "copies/executes/replaces/opens for viewing"
8. "Preferences / Code Editors / SQL Editor / SQL Execution Wrapper"
• "Enable SQL execution wrapper"
• "Before SQL"
• "After SQL"
9. "Preferences / Code Editors / Code Insight"
• "Enabled", "Include DB objects, Code Assistant and Code Explorer data"
• "Show storage arguments" works in Debugger and non-debugger modes
• timer to show or delay the list of Code Insight
10. "Preferences / PL/SQL Debugger"
• "Save breakpoints"
• "Save watches"
11. "Preferences / General / Extract DDL"
• "Text case" = "Unchanged"/"Uppercase"/"Lowercase"/"Init Caps". Note: text font is applied automatically on opening an object DDL in text editor or generating SQL statement by drag&drop from Object Navigator to code editor.
12. "Preferences / Object Wizards" Note: only new GUI of windows (view, collection, trigger, index, sequence, cluster, mat.view, mat.view log, refresh group, index type, operator, queue, dimension, outline, job, library, sched.job, sched.program, sched.chain, sched.schedule, sched.destination, sched.group, sched.window, sched.job class, sched.credential, file watcher, edition, rule, rule set, rule evaluation context, restore point, flashback archive)
• "Break object creation/modification on error"
• "Log the process of object creation/modification" (in Output Window)
• "Automatically show SQL for changes on object change"
13. "Preferences / PL/SQL Profiler"
• "Open Profiler viewer after stopping Profiler"
Set the listed options and your work as developer will be fast and easy because of auto-linked SD tools. Set the indexes to Oracle Documentation and linked topic will open automatically from ora-error message or by popup menu of code editor for any Oracle key-word.
DB ADMIN
1. Use the templates in tools (find object, tkprof shell, export data wizard, import data wizard, compare dbs/schemas/objects, schema extractor, schema compiler, schema analyzer)
2. "Preferences / Session Navigator"
• "Apply last open settings on open"
• "Format SQL"
3. "Preferences / Storage Manager"
• "Apply last open settings on open"
4. "Preferences / Database Examiner"
• "Restore last active page"
• "Autosave datagrid settings"
• "Format SQL"
5. "Preferences / Database Monitor"
• "Restore last active page
• "Alarms", "Email", "Notify when returned to the allowed range"
6. "Preferences / Top Session Locator"
• "Restore last active criteria
• "Apply last open settings on open"
• "Format SQL"
Auto refresh in opened Session Navigator, Database Examiner, Database Monitor, Top Session Locator may be used instead of the "Keep connection alive" option in Preferences. It's a pity that now not all DBA tools send alarms to e-mail like it works in DB Monitor, SmartDataset doesn't have an option to auto refresh data for using it as personal application. But if you set the listed options then your work as DB Admin in SD becomes automated partly.

Unfortunately, no one of the support team in ConquestSS doesn't know all SD abilities and they can't present features properly. So, don't hesitate to type here your comments and questions about settings for useful and fast work in SD.


2018-01-23

Code Review automation

Benefits of Code Review was good listed in the "Getting to Working Software: Code Reviews – Benefits" article from Gil Zilberfeld.
Code Review automation may be done by one value - Maintainability Index "MI" (see "Качество кода одним числом". The most of applications for developers (SQLDetective or TOAD for Oracle developers) count MI even never institutes approved the minimum value - 65 with code comments or 85 for languages without necessity of comments.
As Code Review is a part of white-box testing then I should recommend you the following topics:
* Easy "white-box" testing
* Документор кода или псевдокод
* Call Tree диаграммы в ClearSQL 
* CRUD matrices in Conquest products