SQL Scripting for ETL: Difference between revisions

From QPR ProcessAnalyzer Wiki
Jump to navigation Jump to search
(306698)
Line 119: Line 119:
* IntValue: the integer representation of the selection value (used for object IDs etc). BIGINT.
* IntValue: the integer representation of the selection value (used for object IDs etc). BIGINT.
* Value: the string representation of the selected value. Used for selections that require more complex representation than single integer value. NVARCHAR(MAX).
* Value: the string representation of the selected value. Used for selections that require more complex representation than single integer value. NVARCHAR(MAX).
* Name: the unique name for the selection value. See the table above for the name for each type. Note that there can be multiple rows with the same name if the selection consists of multiple "objects". NVARCHAR(MAX).
* Name: the unique name for the selection value. See the table above for the list of name used for each type. Note that there can be multiple rows with the same name if the selection consists of multiple "objects". NVARCHAR(MAX).
<br/>
<br/>



Revision as of 12:00, 18 May 2016

This page gives general information related to extracting, transforming and loading data in QPR ProcessAnalyzer. The supported commands and their descriptions are listed in Supported QPR ProcessAnalyzer Commands in Scripts.

It is possible to load raw data into QPR ProcessAnalyzer and do the data transformation and loading into QPR ProcessAnalyzer Service via scripts using temporary database tables, so that the resulting transformed data can be used for analyses in QPR ProcessAnalyzer.

A user with the ManageIntegrations and RunScripts permissions can define a script via the Manage Scripts dialog. The script consists of SQL statements and QPR ProcessAnalyzer commands that take the preceding SQL statements as parameters.

Script Variables

The scripts have the following variables available:

  • @_ProjectId: the Id of the project in whose context the script is being run. BIGINT. Undefined if project context has not been specified in script execution parameters.
  • @_ModelId: the Id of the model in whose context the script is being run. BIGINT. Undefined if model context has not been specified in script execution parameters.
  • @_FilterId: the Id of the filter in whose context the script is being run. BIGINT. Undefined if filter context has not been specified in script execution parameters.
  • @_QPRProcessAnalyzerVersion: the QPR Process Analyzer core dll version as string in the format: <major>.<minor>.<build>.<revision>. NVARCHAR(64).
  • @_ScriptingVersion: The scripting version number that identifies the version which was used when script was saved. Can be used for indicating, for example, the version for which the script was originally planned. A script created for newer (bigger) scripting version doesn't necessarily work on a PA server supporting older (smaller) version. INT.
  • @_UserId: the Id of the user running the script. INT.
  • @_ScriptId: Id of the script being run. BIGINT.
  • @_EngineScriptingVersion: The scripting version that identifies the functionalities available from QPR ProcessAnalyzer server. A script created for newer (bigger) scripting version doesn't necessarily work on a QPR ProcessAnalyzer server supporting older (smaller) version. INT.
  • @_DatabaseId: the Id of the database in use. GUID.
  • @_ExceptionOccurred: if there was an exception when running the script, then this value is 1, otherwise 0. INT
  • @_ExceptionType: if there was an exception when running the script, shows the C# class name for the exception, NVARCHAR(MAX), otherwise NULL.
  • @_ExceptionMessage: if there was an exception when running the script, contains a message that would have been displayed, NVARCHAR(MAX), otherwise NULL.
  • @_ExceptionDetails: if there was an exception when running the script, contains the details that would have been displayed, including the system stack trace, NVARCHAR(MAX), otherwise NULL.
  • #_ViewSettings: The Settings shown in the right-hand pane in Excel used to generate the selected view. Note that this doesn't include analysis results or QPR ProcessAnalyzer Server related information, such as FilterId, TotalEventCount, or DatabaseId. Represented as a table two column table variable. The columns are:
    • Name: the name of the parameter. NVARCHAR(440).
    • Value: the value of the parameter. NVARCHAR(MAX).
  • #_Selection: The objects the user has currently selected on the analysis. Supported objects are the event types and transitions in the Flowchart or Path analyses and the Excel cells in the Duration, Profiling, Cases, Variations, Event Types, or Flows analyses. Any filters already applied are included in the selection. The maximum supported amount for the selection is 1000 separate objects and 10000 cells and their values. Represented as a four column table variable. The columns are:
  • Type: the type of the selected object. INT.
Type Description
0 Common. Values for the Common Type are represented as a Value-IntValue pair. See the table on the right for descriptions.
2 Activity. Has the following names and values:
  • SelectedActivities (IntValue): One activity/event type id in every row.
6 Activity Path. Has the following names and values:
  • SelectedActivityPaths (Value): One activity path in every row.
8 Attribute Value. Has the following names and values:
  • SelectedAttributeValues (Value): One attribute value in every row.
10 Case. Has the following names and values:
  • SelectedCases (IntValue): One case id in every row.
12 Count. Has the following names and values:
  • SelectedCounts (IntValue): One variation event type count in every row.
14 Duration. Has the following names and values:
  • SelectedDurations (IntValue): One duration in every row.
16 Transition. Has the following names and values:
  • SelectedTransition (Value): One transition/flow in every row.
18 Variation. Has the following names and values:
  • SelectedVariations (IntValue): One variation in every row.
20 Trends. Has the following names and values:
  • SelectedEventTypeTrends (Value): One selected event type trend with all its selected period identifiers in every row.
  • SelectedTrendPeriodLevel: Selected period level for trend selection, possible values are 0 = Day, 1 = Week, 2 = Month, 3 = Quarter, 4 = Year.
  • SelectedTrendStartDate: Selected start date in ISO format (e.g. 2016-01-28) for the trend selection.
Common Type Value Description
NumberOfActivities The amount of activities in the selection.
NumberOfActivityPaths The amount of activity paths in the selection.
NumberOfAttributeValues The amount of attribute values in the selection.
NumberOfCases The amount of cases in the selection.
NumberOfCounts See the "Group By Event Count" entry in the Variations page.
NumberOfDurations The amount of durations in the selection.
NumberOfTransitions The amount of transitions in the selection.
NumberOfVariations The amount of variations in the selection.
DurationGranularity The duration time unit used in the selection. See the "Group By" entry in the Duration Analysis page for reference.
DurationMaximum The duration limit in the selection. See the "Duration Limit" entry in the Duration Analysis page for reference.
ReversedPaths The value is "1" if the "Predecessors" Direction was selected in the Path Analysis, otherwise "0".
SelectionType What was selected. The value for this parameter is shown on the "Value" column instead of the IntValue column.
  • IntValue: the integer representation of the selection value (used for object IDs etc). BIGINT.
  • Value: the string representation of the selected value. Used for selections that require more complex representation than single integer value. NVARCHAR(MAX).
  • Name: the unique name for the selection value. See the table above for the list of name used for each type. Note that there can be multiple rows with the same name if the selection consists of multiple "objects". NVARCHAR(MAX).


Note that even when a script context hasn't been selected, the variables get their values from a default filter. The default filter is the filter that was last used by the user in the model the user has last opened. If the user hasn't opened any model before, the default filter is taken from the last created model to which the user has access rights.

Example
The following script fragment defines the ProjectId, ModelId, and FilterId parameters by using the script variables:
SELECT @_ProjectId as ProjectId, @_ModelId as ModelId, @_FilterId as FilterId;
Example
The following script gets the View Settings currently in use in the Settings pane in Excel and shows them as a table in a new Excel sheet:
(SELECT * FROM #_ViewSettings)
(SELECT 'SheetName', 'ViewSettings')
--#ShowReport
Example
The following script gets the current selection on the analysis and shows the data as a table in a new Excel sheet:
(SELECT * FROM #_Selection)
(SELECT 'SheetName' , 'Selection')
--#ShowReport
Example
The following script gets various information about the environment and shows them in a new Excel sheet:
SELECT  @_QPRProcessAnalyzerVersion as QPRProcessAnalyzerVersion, @_ScriptingVersion as ScriptingVersion, @_EngineScriptingVersion as EngineScriptingVersion, @_UserId as Userid, @_DatabaseId as DatabaseId
(SELECT 'SheetName', 'Info')
--#ShowReport

Exception Handling

In general, scripts are meant to be developed in such a way that in the end you can run the scripts without any errors. However, sometimes there may be some system issues (timeouts SAP etc.) that can cause for example data extraction scripts to fail. For these kind of situations and for development time and troubleshooting purposes, you can use the CatchOperationExceptions parameter and the @_ExceptionOccurred, @_ExceptionType, @_ExceptionMessage, and @_ExceptionDetails script variables with the QPR ProcessAnalyzer script commands to handle exceptions in ProcessAnalyzer. Out of these, the @_ExceptionOccurred is handy for example in defining some other command to be run in case there was an exception. For SQL errors, the TRY-CATCH error handling should be used.

Note that the CatchOperationExceptions parameter is in effect only for the command it is used with, i.e. it isn't in effect in child scripts or scripts that are run via the --#Exit command. In addition, when there are multiple ProcessAnalyzer script commands in the script, the @_ExceptionOccurred, @_ExceptionType, @_ExceptionMessage, and @_ExceptionDetails script variables get updated each time, i.e. the variable values are available only until the next ProcessAnalyzer command is executed. To use the same variable values in multiple ProcessAnalyzer commands in the script, place the values into a temporary table:

SELECT
@_ExceptionOccurred 'ExceptionOccurred',
@_ExceptionType 'ExceptionType',
@_ExceptionMessage 'ExceptionMessage',
@_ExceptionDetails 'ExceptionDetails'
INTO #PACommandExceptions

SQL Command Support

When transforming data in QPR ProcessAnalyzer Pro (i.e. when connected to the QPR ProcessAnalyzer Service), only temporary tables (#) should be used. Note that global temporary tables (##) should never be used in the SQL scripts, and using them is not allowed. When using QPR ProcessAnalyzer Xpress, these limitations do not apply.

Print

The Print SQL statement can be used to generate log entries into the script execution log.

Running Scripts

A script can be run in the following ways:

Running a Script from the Ribbon

  1. On the QPR tab of the ribbon, click Run.
  2. Select the script to be run from the Script Gallery that opens.

Running a Script from the Manage Scripts Dialog

  1. On the QPR tab of the ribbon, click Manage Scripts.
  2. From the dialog, select the context in which the script you wish to run exists.
  3. Select the script you wish to run.
  4. Click Run.

Terminating Scripts

A script can be terminated by the following ways:

  • The user running the script can click the Cancel button when the script is running.
  • The script can use the "--#Exit" command to stop script execution.
  • A QPR ProcessAnalyzer Administrator user can terminate the script via the Operation Log.
  • The SQL Server System Administrator can kill the session using the script by using e.g. SQL Server Management Studio.
  • The Internet Information Services Administrator can recycle the application pool if the script has caused it to hang. Note however, that this may also cause other requests by other users being processed at the same time to be aborted.
  • The Windows Administrator can kill the w3wp.exe-process processing a problematic script. Note however, that this may also cause other requests by other users being processed at the same time to be aborted.

NOTE!
Terminating the script will not revert any changes the script has already done in the database before the Cancel button is clicked.

Things to Note About Scripts

When writing and using scripts, take the following things into account:

  • Only those lines in the script that start with "--#" (without the quotes) are treated as QPR ProcessAnalyzer Commands, i.e. if there are leading whitespaces before the command, the line is treated as a comment.
  • If you don't define a value for the MaximumCount parameter, 1000 will be used as default, i.e. only the 1000 first rows from a given table or model will be used.
  • When doing more advanced operations with scripts, you may run into the error messages such as: "The data types sql_variant and varchar are incompatible in the add operation.", "Argument data type sql_variant is invalid for argument 1 of like function.", "Argument data type sql_variant is invalid for argument 1 of left function.". This is because case attributes, event attributes, and data inside data tables are sql_variant type data. In order to use them with more advanced operations (e.g. Add), you need to CONVERT or CAST them into some other data type before the operations. See this example.
  • For certain characters in attribute values, you need to use escaping in order to have them interpreted correctly in the script. For more information, see Escaping for Attribute Values.

Troubleshooting Scripts

After a script has been run, the Script Log dialog is shown. You can use it to troubleshoot your script.

Invalid Object Name

  • "Invalid object name" exception is thrown when running a script with #GetAnalysis and #ImportEvents commands. What causes this?
The issue may arise when there are no events to import, i.e. the #GetAnalysis command doesn't create any table. In this case, the missing event table needs to be created in the script between the #GetAnalysis and #ImportEvents commands:
/*This is the GetAnalysis part */
(SELECT 'AnalysisType', '6') UNION ALL
(SELECT 'MaximumCount', '0') UNION ALL
(SELECT 'FilterId', '10') UNION ALL
(SELECT 'SelectedEventAttributes', '*') UNION ALL
(SELECT 'TargetTable', '#AnalysisResult')
--#GetAnalysis

/*Here we create the event table, if it is missing */
IF object_id('tempdb..#AnalysisResult') is  null
BEGIN
CREATE TABLE #AnalysisResult (
CaseName NVARCHAR(MAX),
EventTypeName NVARCHAR(MAX),
TimeStamp DATETIME,
Cost FLOAT,
TotalCost FLOAT
);
END

/*Then we use the ImportEvents */
(SELECT 'ProjectName', 'ExampleProject') UNION ALL
(SELECT 'ModelName', 'ExampleModel')
(SELECT * FROM [#AnalysisResult])
--#ImportEvents

Incorrect Syntax When Using ' Characters

  • SQL error: Incorrect syntax near '
If you get this error message, check the ' characters in the parameter definitions. Note that you cannot use the ' character in the parameter value.

Incorrect Syntax When Running Scripts Copied from QPR ProcessAnalyzer Wiki

  • SQL error: Incorrect syntax
You may get this kind of error message when trying to run a script that you have copied and pasted directly from, for example, the examples given in Supported QPR ProcessAnalyzer Commands in Scripts. This happens because the scripts are then likely to contain non-breaking spaces (encoded as 0xA0 but not visible when pasted to the Script Code field) which cause the running of the scripts to fail as they are not accepted in the SQL syntax.
The solution is to manually remove the non-breaking spaces after copying and pasting the script, so there are no extra spaces at the beginning of each line, for example.

Using "##" in a Script

  • Using "##" in a script is not allowed. Did you mistype temporary table name?
This error message is displayed if the name of the project or model name contains two consecutive # characters (i.e. ##) and you try creating a new project or a model using scripts. Note that you cannot use the ## character in the name of the project or the model.

The ? Character in Project and Model Names

  • A project or model name contains question marks.
The problem arises if you try to, for example, create a project or a model with a name containing multibyte characters using scripts. The created project or model will then include question mark characters instead of multibyte characters. The fix is to add a prefix N' to the name containing multibyte characters (for example, N'【隱藏▲】【純文字檢視】【複製到剪貼簿】'). Another workaround is not to use multibyte characters at all in scripts but instead ProjectId and ModelId, if possible. To do that, you can view the Id column in the Models tab of the Workspace dialog in the same way as described for data tables in Adding an Id Column to the Data Tables List.

Multiple Projects with the Same Name

  • "There are multiple projects with name '<ProjectName>'. Please, specify ProjectId in sandbox script operation: #<Operation>"
This error message is displayed when trying to run a script if you have access to two or several projects with the same name and you refer to the project by name in the script. The fix for resolving this ambiguity is to refer to the project by its ID using the 'ProjectId' parameter instead of 'ProjectName'. An ID is always unique, whereas a name is not.

Multiple Models with the Same Name

  • "There are multiple models with name '<ModelName>'. Please, specify ModelId in sandbox script operation: #<Operation>"
This error message is displayed when trying to run a script if you have access to two or several models with the same name and you refer to the model by name in the script. The fix for resolving this ambiguity is to refer to the model by its ID using the 'ModelId' parameter instead of 'ModelName'. An ID is always unique, whereas a name is not.

Template:UnicodeComparison

  • For example, the following script will show characters that are treated similar as zero "0":
DECLARE @referenceAscii int = 0

IF object_id('tempdb..#ids') is null 
CREATE TABLE #ids ( id int)

DECLARE @i int = 0
WHILE @i < 70000 BEGIN
    SET @i = @i + 1
    INSERT #ids VALUES (@i)
END

select * FROM (
  select 
    sys.fn_varbintohexstr(CONVERT(varBINARY(8), id)) as CharacterAsHex,
    id as ASCIICode,
    nchar(id) as Character,
   (CASE WHEN Nchar(@referenceAscii) = NCHAR(id) THEN 1 ELSE 0 END) as ShownAsSimilar 
  FROM #ids ) as x
where x.ShownAsSimilar = 1
--#ShowReport

Client Exception When Using #ImportSapQuery Command

  • Limitations in size of SAP query result
The SAP system has limitations as to how much data can be queried. The workaround for the error is to reduce the amount of data to be queried using 'SapRowcount', 'SapRowskips', 'SapWhereClauseSelect', 'SapFieldNames' and 'SapFunction' parameters. See --#ImportSapQuery for parameter explanations.
  • "Client exception" is thrown when running a script with #ImportSapQuery command using the 'SapWhereClauseSelect' parameter.
For example, the following error text can be displayed:
 #ImportSapQuery: SAP.Middleware.Connector.RfcAbapRuntimeException: SAP.Middleware.Connector.RfcAbapRuntimeException:
 Error in module RSQL of the database interface
   at SAP.Middleware.Connector.RfcConnection.ThrowRfcErrorMsg()
   at SAP.Middleware.Connector.RfcConnection.ReadBytes(Byte* buffer, Int32 count)
   at SAP.Middleware.Connector.RfcConnection.ReadRfcIDBegin(Int32& length)
   at SAP.Middleware.Connector.RfcConnection.ReadUpTo(RFCGET readState, RfcFunction function, RFCID toRid)
   at SAP.Middleware.Connector.RfcConnection.RfcReceive(RfcFunction function)
   at SAP.Middleware.Connector.RfcFunction.RfcDeserialize(RfcConnection conn, IRfcIOStream stream)
   at SAP.Middleware.Connector.RfcFunction.RfcCallReceive(RfcConnection conn, IRfcIOStream stream, RFCID rid)
   at SAP.Middleware.Connector.RfcFunction.Invoke(RfcDestination destination)
   at Qpr.ProcessAnalyzer.Common.Integration.Sap.SapQuery(RfcDestination destination, Action`2 getSapWhereClauseSelect, Boolean enableStreamCompression, IDictionary`2 parameters)
   System.ServiceModel.FaultException`1[Qpr.Utils.SapError]: SAP.Middleware.Connector.RfcAbapRuntimeException: Error in module RSQL of the database interface
   (Fault Detail is equal to SAP.Middleware.Connector.RfcAbapRuntimeException: Error in module RSQL of the database interface
This issue may arise when you are extracting data from SAP and the size of 'SapWhereClauseSelect' parameter value is too large. Reduce the size of the 'SapWhereClauseSelect' value.

Supported QPR ProcessAnalyzer Commands in Scripts

For a list of supported commands and their descriptions, see page Supported QPR ProcessAnalyzer Commands in Scripts.

QPR ProcessAnalyzer ETL Tutorial

There is also an ETL tutorial for learning the basics of creating ETL scripts in SQL and using them in QPR ProcessAnalyzer.

ETL Script Examples

For more examples, see ETL Script Examples.