Computer lessons

Feature of the substring() function. Feature of the substring() function Using the query builder

In the 1C:Enterprise query language, the function SUBSTRING() V format SUBSTRING(<Исходная строка>, <Начало>, <Длина>) can be applied to string data and allows you to select a fragment<Исходной строки>, starting with the character number<Начало>(characters in a line are numbered starting from 1) and length<Длина>characters. The result of the calculation of the SUBSTRING() function has a string type of variable length, and the length will be considered unlimited if<Исходная строка>has unlimited length and parameter<Длина>is not a constant or greater than 1024.

Calculation of the SUBSTRING() function on SQL server:
In the client-server version of the work, the SUBSTRING() function is implemented using the SUBSTRING() function of the corresponding SQL statement, passed to the SQL Server database server, which calculates the type of the result of the SUBSTRING() function using complex rules depending on the type and values ​​of its parameters, as well as depending on the context in which it is used.

In most cases, these rules do not affect the execution of a 1C:Enterprise query, however, there are cases when the maximum length of the result string calculated by SQL Server is essential for query execution. It is important to keep in mind that in some contexts when using the SUBSTRING() function, the maximum length of its result may be equal to the maximum length of a limited-length string, which in SQL Server is 4000 characters. This may cause the request to terminate unexpectedly.

For example, the request:
Code 1C v 8.x SELECT
CHOICE

ELSE NULL
THE END AS A Presentation,
CHOICE
WHEN Type = &LegalAddressIndividual
THEN SUBSTRING(Representation, 0, 200)
ELSE NULL
END AS Presentation1
FROM
SORT BY
Performance,
Performance1
terminates abnormally with the message DBMS error:
Microsoft OLE DB Provider for SQL Server: Warning: The query processor could not produce a query plan from the optimizer because the total length of all the columns in the GROUP BY or ORDER BY clause exceeds 8000 bytes.
HRESULT=80040E14, SQLSTATE=42000, native=8618

This occurs because Microsoft SQL Server calculates the maximum length of the string that results from the expression:
Code 1C v 8.x SELECTION
WHEN Type = &LegalAddressIndividual
THEN SUBSTRING(Representation, 0, 200)
ELSE NULL
THE END AS A Presentation,
equals 4000 characters. Therefore, the length of a record consisting of two such fields exceeds the 8000 bytes allowed for the sort operation.

Due to the described peculiarity of the execution of the SUBSTRING() function on SQL Server, using the SUBSTRING() function to convert strings of unlimited length to strings of limited length is not recommended. Instead, it is better to use the cast operator EXPRESS(). In particular, the above example can be rewritten as:
Code 1C v 8.x SELECT
CHOICE
WHEN Type = &LegalAddressIndividual
ELSE NULL
THE END AS A Presentation,
CHOICE
WHEN Type = &LegalAddressIndividual
THEN EXPRESS(Representation AS String(200))
ELSE NULL
END AS Presentation1
FROM
Register of Information. Contact Information HOW Contact Information
SORT BY
Performance,
Performance1

There are few mechanisms for working with strings in 1C queries. First, the lines can be added. Secondly, you can take a substring from a string. Thirdly, strings can be compared, including by pattern. That's probably all that can be done with strings.

String addition

To add rows in a query, the “+” operation is used. You can only add strings of limited length.

SELECT "Name: " + Counterparties. Name AS Column 1 FROM Directory. Counterparties AS Counterparties WHERE Counterparties. Link = &Link

Substring function

SUBSTRING(<Строка>, <НачальнаяПозиция>, <Длина>)

An analogue of the Environment() function from the object model. The Substring() function can be applied to string data and allows you to select a fragment <Строки> , starting with the character number <НачальнаяПозиция> (characters in a line are numbered starting from 1) and length <Длина> characters. The result of the function calculation has a variable-length string type, and the length will be considered unlimited if <Строка> has unlimited length and parameter <Длина> is not a constant or greater than 1024.

If the length of the string is less than specified in the second parameter, then the function will return an empty string.

Attention! Using the SUBSTRING() function to convert strings of unlimited length to strings of limited length is not recommended. Instead, it is better to use the cast operator EXPRESS().

Function Similar

If we need to make sure that a string attribute meets certain criteria, we compare it:

SELECT Counterparties. Name AS Column 1 FROM Directory. Counterparties AS Counterparties WHERE Counterparties. Name = "Gazprom"

But what if you need a more subtle comparison? Not just equality or inequality, but similarity to a certain pattern? This is exactly what the SIMILAR function was created for.

LIKE — Operator for checking a string for similarity to a pattern. Analogue of LIKE in SQL.

The SIMILAR operator allows you to compare the value of the expression specified to the left of it with the pattern string specified to the right. The value of the expression must be of type string. If the value of the expression matches the pattern, the result of the operator will be TRUE, otherwise it will be FALSE.

The following characters in the template string are service characters and have a meaning different from the string character:

  • % (percent): a sequence containing any number of arbitrary characters;
  • _ (underscore): one arbitrary character;
  • […] (one or more characters in square brackets): any single character listed inside the square brackets. The enumeration may contain ranges, for example a-z, meaning an arbitrary character included in the range, including the ends of the range;
  • [^...] (in square brackets a negation sign followed by one or more characters): any single character other than those listed following the negation sign.

Any other symbol means itself and does not carry any additional load. If one of the listed characters needs to be written as itself, then it must be preceded by<Спецсимвол>. Myself<Спецсимвол>(any suitable character) is defined in the same statement after the SPECIAL CHARACTER keyword.

The query language in 1C 8 is a simplified analogue of the well-known “structured programming language” (as it is more often called, SQL). But in 1C it is used only for reading data; an object data model is used to change data.

Another interesting difference is the Russian syntax. Although in fact you can use English-language constructions.

Example request:

CHOOSE
Banks.Name,
Banks.CorrAccount
FROM
Directory.Banks HOW Banks

This request will allow us to see information about the name and correspondent account of all banks existing in the database.

Query language is the simplest and most effective way to obtain information. As can be seen from the example above, in the query language you need to use metadata names (this is a list of system objects that make up the configuration, i.e. directories, documents, registers, etc.).

Description of query language constructs

Query structure

To obtain data, it is enough to use the “SELECT” and “FROM” constructions. The simplest request looks like this:

SELECT * FROM Directories.Nomenclature

Where “*” means selecting all fields of the table, and Directories.Nomenclature – the name of the table in the database.

Let's look at a more complex and general example:

CHOOSE
<ИмяПоля1>HOW<ПредставлениеПоля1>,
Sum(<ИмяПоля2>) HOW<ПредставлениеПоля2>
FROM
<ИмяТаблицы1>HOW<ПредставлениеТаблицы1>
<ТипСоединения>COMPOUND<ИмяТаблицы2>HOW<ПредставлениеТаблицы2>
BY<УсловиеСоединениеТаблиц>

WHERE
<УсловиеОтбораДанных>

GROUP BY
<ИмяПоля1>

SORT BY
<ИмяПоля1>

RESULTS
<ИмяПоля2>
BY
<ИмяПоля1>

In this query, we select the data of the fields “FieldName1” and “FieldName1” from the tables “TableName1” and “TableName”, assign synonyms to the fields using the “HOW” operator, and connect them using a certain condition “TableConnectionCondition”.

From the received data, we select only data that meets the condition from “WHERE” “Data Selection Condition”. Next, we group the request by the field “Field Name1”, while summing “Field Name2”. We create totals for the field “Field Name1” and the final field “Field Name2”.

The last step is to sort the request using the ORDER BY construct.

General designs

Let's look at the general structures of the 1C 8.2 query language.

FIRSTn

Using this operator, you can get the n number of first records. The order of the records is determined by the order in the query.

SELECT FIRST 100
Banks.Name,
Banks. Code AS BIC
FROM
Directory.Banks HOW Banks
SORT BY
Banks.Name

The request will receive the first 100 entries of the “Banks” directory, sorted alphabetically.

ALLOWED

This design is relevant for working with the mechanism. The essence of the mechanism is to restrict reading (and other actions) to users for specific records in a database table, and not the table as a whole.

If a user tries to use a query to read records that are inaccessible to him, he will receive an error message. To avoid this, you should use the “ALLOWED” construction, i.e. the request will read only records that are allowed to it.

SELECT ALLOWED
Repository of Additional Information. Link
FROM
Directory.Repository of Additional Information

VARIOUS

Using “DIFFERENT” will prevent duplicate lines from entering the 1C query result. Duplication means that all request fields match.

SELECT FIRST 100
Banks.Name,
Banks. Code AS BIC
FROM
Directory.Banks HOW Banks

EmptyTable

This construction is used very rarely to combine queries. When joining, you may need to specify an empty nested table in one of the tables. The “EmptyTable” operator is just right for this.

Example from 1C 8 help:

SELECT Link.Number, EMPTY TABLE.(No., Item, Quantity) AS Composition
FROM Document.Expense Invoice
COMBINE EVERYTHING
SELECT Link.Number, Contents.(LineNumber, Product, Quantity)
FROM Document.Invoice Document.Invoice.Composition.*

ISNULL

A very useful feature that allows you to avoid many mistakes. YesNULL() allows you to replace the NULL value with the desired one. Very often used in checking for the presence of a value in joined tables, for example:

CHOOSE
Nomenclature Ref. Link,
IsNULL(Item Remaining.QuantityRemaining,0) AS QuantityRemaining
FROM


Can be used in other ways. For example, if for each row it is not known in which table the value exists:

ISNULL(InvoiceReceived.Date, InvoiceIssued.Date)

HOW is an operator that allows us to assign a name (synonym) to a table or field. We saw an example of use above.

These constructions are very similar - they allow you to get a string representation of the desired value. The only difference is that REPRESENTATION converts any values ​​to a string type, while REPRESENTATIONREF converts only reference values. REFERENCE REPRESENTATION is recommended to be used in data composition system queries for optimization, unless, of course, the reference data field is planned to be used in selections.

CHOOSE
View(Link), //string, for example “Advance report No. 123 dated 10/10/2015
View(DeletionMark) AS DeleteMarkText, //string, “Yes” or “No”
ViewReferences(DeletionMark) AS DeleteMarkBoolean //boolean, True or False
FROM
Document.Advance Report

EXPRESS

Express allows you to convert field values ​​to the desired data type. You can convert a value to either a primitive type or a reference type.

Express for a reference type is used to restrict the requested data types in fields of a complex type, often used to optimize system performance. Example:

EXPRESS(TableCost.Subconto1 AS Directory.Cost Items).Type of ActivityForTaxAccountingCosts

For primitive types, this function is often used to limit the number of characters in fields of unlimited length (such fields cannot be compared with). To avoid the error " Invalid parameters in comparison operation. You can't compare fields
unlimited length and fields of incompatible types
", you need to express such fields as follows:

EXPRESS(Comment AS Line(150))

DIFFERENCEDATE

Get 267 video lessons on 1C for free:

An example of using IS NULL in a 1C request:

CHOOSE FROM
Ref
LEFT CONNECTION RegisterAccumulations.ProductsInWarehouses.Remaining AS Product Remaining
Software NomenclatureRef.Link = Sold GoodsCommitteesRemains.Nomenclature
WHERE NOT Remaining Products. QuantityRemaining IS NULL

The data type in a query can be determined by using the TYPE() and VALUETYPE() functions, or by using the logical REFERENCE operator. The two functions are similar.

Predefined values

In addition to using passed parameters in queries in the 1C query language, you can use predefined values ​​or . For example, transfers, predefined directories, charts of accounts, and so on. For this, the “Value()” construct is used.

Usage example:

WHERE Nomenclature.Type of Nomenclature = Value(Directory.Types of Nomenclature.Product)

WHERE Counterparties.Type of Contact Information = Value(Enumeration.Types of Contact Information.Phone)

WHERE Account Balances.Accounting Account = Value(Chart of Accounts.Profit.ProfitsLoss)

Connections

There are 4 types of connections: LEFT, RIGHT, COMPLETE, INTERNAL.

LEFT and RIGHT CONNECTION

Joins are used to link two tables based on a specific condition. Feature when LEFT JOIN is that we take the first specified table in its entirety and conditionally bind the second table. The fields of the second table that could not be bound by condition are filled with the value NULL.

For example:

It will return the entire table of Counterparties and fill in the “Bank” field only in those places where the condition “Counterparties.Name = Banks.Name” will be met. If the condition is not met, the Bank field will be set to NULL.

RIGHT JOIN in 1C language absolutely similar LEFT connection, with the exception of one difference - in RIGHT OF CONNECTION The “main” table is the second, not the first.

FULL CONNECTION

FULL CONNECTION differs from left and right in that it displays all records from two tables and connects only those that it can connect by condition.

For example:

FROM

FULL CONNECTION
Directory.Banks HOW Banks

BY

The query language will return both tables completely only if the condition to join the records is met. Unlike a left/right join, it is possible for NULL to appear in two fields.

INNER JOIN

INNER JOIN differs from the full one in that it displays only those records that could be connected according to a given condition.

For example:

FROM
Directory. Counterparties AS Clients

INNER JOIN
Directory.Banks HOW Banks

BY
Clients.Name = Banks.Name

This query will return only rows in which the bank and counterparty have the same name.

Associations

The JOIN and JOIN ALL constructs combine two results into one. Those. the result of performing two will be “merged” into one, common one.

That is, the system works exactly the same as regular ones, only for a temporary table.

How to use INDEX BY

However, one point should be taken into account. Building an index on a temporary table also takes time to complete. Therefore, it is advisable to use the “ ” construction only if it is known for sure that there will be more than 1-2 records in the temporary table. Otherwise, the effect may be the opposite - the performance of indexed fields does not compensate for the time it takes to build the index.

CHOOSE
Currency rates Latest cross-section. Currency AS Currency,
Currency rates Latest cross-section.
PUT Currency Rates
FROM
Information Register.Currency Rates.Last Slice(&Period,) AS Currency RatesLast Slice
INDEX BY
Currency
;
CHOOSE
PricesNomenclature.Nomenclature,
PricesNomenclatures.Price,
PricesNomenclatures.Currency,
Currency rates.Rate
FROM
Information Register.Nomenclature Prices.Last Slice(&Period,
Nomenclature B (&Nomenclature) AND PriceType = &PriceType) AS PriceNomenclature
LEFT JOIN Currency Rates AS Currency Rates
Software PricesNomenclatures.Currency = Currency Rates.Currency

Grouping

The 1C query language allows you to use special aggregate functions when grouping query results. Grouping can also be used without aggregate functions to “eliminate” duplicates.

The following functions exist:

Amount, Quantity, Number of different, Maximum, Minimum, Average.

Example #1:

CHOOSE
Sales of Goods and Services Goods. Nomenclature,
SUM(Sales of GoodsServicesGoods.Quantity) AS Quantity,
SUM(Sales of GoodsServicesGoods.Amount) AS Amount
FROM

GROUP BY
Sales of Goods and Services Goods. Nomenclature

The request receives all lines with goods and summarizes them by quantity and amounts by item.

Example No. 2

CHOOSE
Banks.Code,
QUANTITY(DIFFERENT Banks.Link) AS Number Of Duplicates
FROM
Directory.Banks HOW Banks
GROUP BY
Banks.Code

This example will display a list of BICs in the “Banks” directory and show how many duplicates exist for each of them.

Results

Results are a way to obtain data from a system with a hierarchical structure. Aggregate functions can be used for summary fields, just as for groupings.

One of the most popular ways to use results in practice is batch write-off of goods.

CHOOSE




FROM
Document. Sales of Goods and Services. Goods HOW to Sale of Goods and Services Goods
SORT BY

RESULTS
SUM(Quantity),
SUM(Sum)
BY
Nomenclature

The result of the query will be the following hierarchical:

General results

If you need to get totals for all “totals”, use the “GENERAL” operator.

CHOOSE
Sales of Goods and Services Goods. Nomenclature AS Nomenclature,
Sales of Goods and Services Goods. Link AS Document,
Sales of Goods and Services Goods. Quantity AS Quantity,
Sales of Goods and Services Goods. Amount AS Amount
FROM
Document. Sales of Goods and Services. Goods HOW to Sale of Goods and Services Goods
SORT BY
Sales of Goods and Services Goods. Link. Date
RESULTS
SUM(Quantity),
SUM(Sum)
BY
ARE COMMON,
Nomenclature

As a result of executing the request, we get the following result:

In which 1 level of grouping is the aggregation of all necessary fields.

Arranging

The ORDER BY operator is used to sort the result of a query.

Sorting for primitive types (string, number, boolean) follows the usual rules. For reference type fields, sorting occurs by the internal representation of the link (the unique identifier), rather than by code or by reference representation.

CHOOSE

FROM
Directory.Nomenclature AS Nomenclature
SORT BY
Name

The request will display a list of names in the nomenclature directory, sorted alphabetically.

Auto-order

The result of a query without sorting is a chaotically presented set of rows. 1C platform developers do not guarantee that rows will be output in the same sequence when executing identical queries.

If you need to display table records in a constant order, you must use the Auto-Order construct.

CHOOSE
Nomenclature.Name AS Name
FROM
Directory.Nomenclature AS Nomenclature
AUTO ORDER

Virtual tables

Virtual tables in 1C are a unique feature of the 1C query language that is not found in other similar syntaxes. A virtual table is a quick way to obtain profile information from registers.

Each register type has its own set of virtual tables, which may differ depending on the register settings.

  • cut of the first;
  • cut of the latter.
  • leftovers;
  • revolutions;
  • balances and turnover.
  • movements from subconto;
  • revolutions;
  • speed Dt Kt;
  • leftovers;
  • balances and turnover
  • subconto.
  • base;
  • graph data;
  • actual period of validity.

For the solution developer, the data is taken from one (virtual) table, but in fact the 1C platform takes from many tables, transforming them into the required form.

CHOOSE
Products in Warehouses Remains and Turnover. Nomenclature,
ProductsInWarehousesRemainingAndTurnover.QuantityInitialRemaining,
ProductsInWarehousesRemainsAndTurnover.QuantityTurnover,
GoodsInWarehousesRemainsAndTurnover.QuantityIncoming,
GoodsInWarehousesRemainsAndTurnover.QuantityConsumption,
ProductsInWarehousesRemainingsAndTurnover.QuantityFinalRemaining
FROM
RegisterAccumulations.GoodsInWarehouses.RemainsAndTurnover AS GoodsInWarehousesRemainsAndTurnover

This query allows you to quickly retrieve a large amount of data.

Virtual Table Options

A very important aspect of working with virtual tables is the use of parameters. Virtual table parameters are specialized parameters for selection and configuration.

For such tables, it is considered incorrect to use selection in the “WHERE” construction. In addition to the fact that the query becomes suboptimal, it is possible to receive incorrect data.

An example of using these parameters:

Register of Accumulations. Goods in Warehouses. Balances and Turnovers (& Beginning of the Period, & End of the Period, Month, Movements and Borders of the Period, Nomenclature = & Required Nomenclature)

Algorithm for virtual tables

For example, the most used virtual table of the “Remains” type stores data from two physical tables – balances and movements.

When using a virtual table, the system performs the following manipulations:

  1. We get the closest calculated value in terms of date and measurements in the totals table.
  2. We “add” the amount from the movement table to the amount from the totals table.


Such simple actions can significantly improve the performance of the system as a whole.

Using the Query Builder

Query Builder– a tool built into the 1C Enterprise system that greatly facilitates the development of database queries.

The query builder has a fairly simple, intuitive interface. Nevertheless, let's look at using the query constructor in more detail.

The query text constructor is launched from the context menu (right mouse button) in the desired place in the program code.

Description of the 1C request constructor

Let's look at each tab of the designer in more detail. The exception is the Builder tab, which is a topic for another discussion.

Tables and Fields tab

This tab specifies the data source and fields that need to be displayed in the report. In essence, the constructions SELECT.. FROM are described here.

The source can be a physical database table, a virtual register table, temporary tables, nested queries, etc.

In the context menu of virtual tables, you can set virtual table parameters:

Connections tab

The tab is used to describe connections of several tables and creates constructions with the word CONNECTION.

Grouping tab

On this tab, the system allows you to group and summarize the required fields of the table result. Describes the use of the constructions GROUP BY, SUM, MINIMUM, AVERAGE, MAXIMUM, QUANTITY, NUMBER OF DIFFERENT.

Conditions tab

Responsible for everything that comes in the request text after the WHERE construction, i.e. for all the conditions imposed on the received data.

Advanced tab

Tab Additionally replete with all sorts of parameters that are very important. Let's look at each of the properties.

Grouping Selecting records:

  • First N– a parameter that returns only N records to the query (the FIRST operator)
  • No duplicates– ensures the uniqueness of the received records (DIFFERENT operator)
  • Allowed– allows you to select only those records that the system allows you to select taking into account (ALLOWED construction)

Grouping Request type determines what type of request will be: data retrieval, creation of a temporary table, or destruction of a temporary table.

Below there is a flag Lock received data for later modification. It allows you to enable the ability to set data locking, which ensures the safety of data from the moment it is read until it is changed (relevant only for the Automatic locking mode, design FOR CHANGE).

Joins/Aliases Tab

On this tab of the query designer, you can set the ability to join different tables and aliases (the HOW construct). The tables are indicated on the left side. If you set the flags opposite the table, the UNITE construction will be used, otherwise - UNITE ALL (differences between the two methods). On the right side, the correspondence of fields in different tables is indicated; if the correspondence is not specified, the query will return NULL.

Order tab

This specifies the order in which the values ​​are sorted (ORDER BY) - descending (DESC) or ascending (ASC).

There is also an interesting flag - Auto-order(in the request - AUTO ORDERING). By default, the 1C system displays data in a “chaotic” order. If you set this flag, the system will sort data by internal data.

Query Batch tab

On the query designer tab, you can create new ones, and also use it as a navigation. In the request text, packets are separated by the symbol “;” (comma).

“Query” button in the query designer

In the lower left corner of the request designer there is a Request button, with which you can view the request text at any time:

In this window, you can make adjustments to the request and execute it.


Using the Query Console

The Query Console is a simple and convenient way to debug complex queries and quickly obtain information. In this article, I will try to describe how to use the Query Console and provide a link to download the Query Console.

Let's take a closer look at this tool.

Download 1C query console

First of all, to start working with the query console, you need to download it from somewhere. Treatments are usually divided into two types - controlled forms and conventional ones (or, sometimes, they are called 8.1 and 8.2/8.3).

I tried to combine these two views in one processing - the desired form opens in the desired operating mode (in managed mode, the console only works in thick mode).

Description of the 1C query console

Let's start looking at the query console with a description of the main processing panel:

In the query console header, you can see the execution time of the last query with millisecond accuracy, this allows you to compare different designs in terms of performance.

The first group of buttons in the command bar is responsible for saving current queries to an external file. This is very convenient; you can always return to writing a complex request. Or, for example, store a list of typical examples of certain designs.

On the left, in the “Request” field, you can create new requests and save them in a tree structure. The second group of buttons is responsible for managing the list of requests. Using it you can create, copy, delete, move a request.

  • Executerequest– simple execution and results
  • Execute package– allows you to view all intermediate queries in a batch of queries
  • Viewing temporary tables– allows you to see the results that temporary queries return on a table

Request parameters:

Allows you to set the current parameters for the request.

In the query parameters window, the following is interesting:

  • Button Get from request automatically finds all parameters in the request for the convenience of the developer.
  • Flag Common parameters for all requests– when installed, its processing does not clear the parameters when moving from request to request in the general list of requests.

Set a parameter with a list of values It’s very simple, just when choosing a parameter value, click on the clear value button (cross), the system will prompt you to select the data type, where you need to select “Value List”:

Also in the top panel there is a button for calling up the query console settings:

Here you can specify parameters for autosaving queries and query execution parameters.

The request text is entered into the console request field. This can be done by simply typing a query test or by calling a special tool - the query designer.

The 1C 8 query designer is called from the context menu (right mouse button) when you click on the input field:

This menu also has such useful functions as clearing or adding line breaks (“|”) to the request, or receiving the request code in this convenient form:

Request = New Request;
Request.Text = ”
|SELECT
| Currencies.Link
|FROM
| Directory.Currencies AS Currencies”;
RequestResult = Request.Execute();

The lower field of the query console displays the query result field, which is why this processing was created:



Also, the query console, in addition to the list, can display data in the form of a tree - for queries containing totals.

Query optimization

One of the most important points in increasing the productivity of 1C enterprise 8.3 is optimizationrequests. This point is also very important when passing the certification. Below we will talk about typical reasons for non-optimal query performance and optimization methods.

Selections in a virtual table using the WHERE construct

It is necessary to apply filters to the virtual table details only through the VT parameters. Under no circumstances should you use the WHERE construct for selection in a virtual table; this is a serious mistake from an optimization point of view. In the case of selection using WHERE, in fact, the system will receive ALL records and only then select the necessary ones.

RIGHT:

CHOOSE

FROM
Register of Accumulations. Mutual settlements with Participants of Organizations. Balances (
,
Organization = &Organization
AND Individual = &Individual) HOW Mutual settlements with Participants of Organizations Balances

WRONG:

CHOOSE
Mutual settlements with Participants of Organizations Balances. Amount Balance
FROM
Register of Accumulations. Mutual settlements with Participants of Organizations. Balances (,) HOW Mutual settlements with Participants of Organizations Balances
WHERE
Mutual settlements with Participants of Organizations Balances. Organization = & Organization
AND Mutual settlements with Participants of Organizations Balances. Individual = &Individual

Getting the value of a field of a complex type using a dot

When receiving data of a complex type in a query through a dot, the system connects with a left join exactly as many tables as there are types possible in the field of the complex type.

For example, it is highly undesirable for optimization to access the register record field – registrar. The registrar has a composite data type, among which are all possible document types that can write data to the register.

WRONG:

CHOOSE
Record Set.Recorder.Date,
RecordSet.Quantity
FROM
RegisterAccumulations.ProductsOrganizations AS SetRecords

That is, in fact, such a query will access not one table, but 22 database tables (this register has 21 registrar types).

RIGHT:

CHOOSE
CHOICE
WHEN ProductsOrg.Registrar LINK Document.Sales of Products and Services
THEN EXPRESS(ProductsOrganization.Registrar AS Document.Sales of GoodsServices).Date
WHEN GoodsOrg.Registrar LINK Document.Receipt of GoodsServices
THEN EXPRESS(GoodsOrg.Registrar AS Document.Receipt of GoodsServices).Date
END AS DATE,
ProductsOrg.Quantity
FROM
RegisterAccumulations.ProductsOrganizations AS ProductsOrganization

Or the second option is to add such information to the details, for example, in our case, adding a date.

RIGHT:

CHOOSE
ProductsOrganizations.Date,
ProductsOrganizations.Quantity
FROM
Register of Accumulations. Goods of Organizations AS Goods of Organizations

Subqueries in a join condition

For optimization, it is unacceptable to use subqueries in join conditions; this significantly slows down the query. It is advisable to use VT in such cases. To connect, you need to use only metadata and VT objects, having previously indexed them by connection fields.

WRONG:

CHOOSE …

LEFT JOIN (
SELECT FROM RegisterInformation.Limits
WHERE …
GROUP BY...
) BY …

RIGHT:

CHOOSE …
PUT Limits
FROM Information Register.Limits
WHERE …
GROUP BY...
INDEX BY...;

CHOOSE …
FROM Document. Sales of Goods and Services
LEFT JOIN Limits
BY …;

Joining Records with Virtual Tables

There are situations when, when connecting a virtual table to others, the system does not work optimally. In this case, to optimize the performance of the query, you can try placing the virtual table in a temporary table, not forgetting to index the joined fields in the temporary table query. This is due to the fact that VTs are often contained in several physical DBMS tables; as a result, a subquery is compiled to select them, and the problem turns out to be similar to the previous point.

Using selections based on non-indexed fields

One of the most common mistakes when writing queries is using conditions on non-indexed fields, this contradicts query optimization rules. The DBMS cannot execute a query optimally if the query includes selection on non-indexable fields. If you take a temporary table, you also need to index the connection fields.

There must be a suitable index for each condition. A suitable index is one that satisfies the following requirements:

  1. The index contains all the fields listed in the condition.
  2. These fields are at the very beginning of the index.
  3. These selections are consecutive, that is, values ​​that are not involved in the query condition are not “wedged” between them.

If the DBMS does not select the correct indexes, the entire table will be scanned - this will have a very negative impact on performance and can lead to prolonged blocking of the entire set of records.

Using logical OR in conditions

That's all, this article covered the basic aspects of query optimization that every 1C expert should know.

A very useful free video course on query development and optimization, I strongly recommend for beginners and more!

Let's look at the rest now.

Functions for working with strings in 1C queries

There are few functions and operators for working with string data in 1C queries.

Firstly, strings in queries can be added. To do this, use the “+” operator:

Request. Text = "SELECT
" "Line: " " + Source.Name
;

Secondly, you can select part of the line. To do this, use the function SUBSTRUCTION. The function is similar to the built-in 1C language. It has three parameters:

  1. Source string.
  2. The number of the character with which the selected line should begin.
  3. Characters.

Request. Text= "CHOOSE
SUBSTRING("
"Line: " ", 4, 3) AS A Result"; // Result: oka

Function ISNULL

NULL is a special data type on the 1C:Enterprise platform. It is also the only possible value of this type. NULL can appear in queries in several cases: when connecting query sources, if a corresponding value was not found in one of the tables; when accessing the details of a non-existent object; if NULL was specified in the list of query fields (for example, when combining selection results from several tables), etc.

Because NULL is neither null, nor the empty string, nor even a value Undefined, it is often useful to replace it with some more useful data type. This is what the function is designed for. ISNULL.

It has two parameters:

  1. The value being checked.
  2. The value to replace the first parameter with if it turns out to be NULL.

Request. Text= "CHOOSE
ISNULL(Source.Remainder, 0) AS Remainder"
; // If the result of the request is the field remainder = NULL,
// then it will be replaced by 0, and you can perform mathematical operations with it

Functions PERFORMANCE And INTRODUCTIONLINKS

These functions are designed to obtain string representations of various values. That is, they convert references, numbers, booleans, etc. into plain text. The difference between them is that the function PERFORMANCE converts any data types to text (string), and the function INTRODUCTIONLINKS- only links, and returns the remaining values ​​as is, not converted.

Request. Text= "CHOOSE
REPRESENTATION(TRUE) AS Boolean,
REPRESENTATION (4) AS A Number,
REPRESENTATION (Source.Link) AS Link,
REPRESENTATION(DATETIME(2016,10,07)) AS Date"
;
// Boolean = "Yes", Number = "4", Link = "Document Cash receipt order No.... from..."
// Date="07.10.2016 0:00:00"

Request. Text= "CHOOSE
REPRESENTATIONREFERENCE(TRUE) AS Boolean,
REPRESENTATIONREFERENCE(4) AS NUMBER
PRESENTINGLINK(Source.Link) AS Link,
REPRESENTATIONREFERENCE(DATETIME(2016,10,07)) AS Date"
;
// Boolean = TRUE, Number = 4, Link = "Document Cash receipt order No.... from..."
// Date=07.10.2016 0:00:00

Functions TYPE And TYPE VALUES

Function TYPE returns the 1C:Enterprise platform data type.

Request. Text= "CHOOSE
TYPE (Number)
TYPE (String),
TYPE (Document. Expenditure Cash Order)"
;

Function TYPE VALUES returns the type of the value passed to it.

Request. Text= "CHOOSE
VALUES TYPE (5) AS Number,
TYPE ("
"Line" ") AS String,
TYPE (Source.Link) AS Reference
From the Directory.Source AS Source"
;
//Number=Number, String=String, Directory = DirectoryLink.Source

These functions are convenient to use, for example, when you need to find out whether a field received in a request is a value of some type. For example, let’s get the contact information of counterparties from the ContactInformation information register (contacts of not only counterparties, but also organizations, individuals, etc. are stored there):

Request. Text= "CHOOSE

FROM

WHERE
VALUES TYPE(ContactInformation.Object) = TYPE(Directory.Counterparties)"
;

Function MEANING

Function Meaning allows you to use 1C configuration objects directly in a request, without using .

Let's add one more condition to the previous example. You only need to get the phone numbers of your counterparties.

Request. Text= "CHOOSE
ContactInformation.Introduction
FROM
Register of Information. Contact Information HOW Contact Information
WHERE
VALUES TYPE(ContactInformation.Object) = TYPE(Directory.Counterparties)
AND ContactInfo.Type = VALUE(Enum.ContactInfoTypes.Phone)"
;

It should be noted that this function can only be used with predefined values, i.e. with values ​​that can be accessed directly from the configurator. That is, the function MEANING cannot be used with directory elements created by users, but can work with enumerations, with predefined directory elements, with values EmptyLink.

Operator LINK

Operator LINK is designed to check the values ​​returned by a request to see if they belong to a specific reference type. The same task can be accomplished using functions TYPE And TYPE VALUES(which have a wider scope and were discussed above).

For example, the task of selecting contact information for counterparties could be solved this way:

Request. Text= "CHOOSE
ContactInformation.Introduction
FROM
Register of Information. Contact Information HOW Contact Information
WHERE
ContactInformation.Object LINK Directory.Counterparties"
;

Operator EXPRESS

Operator EXPRESS used in 1C queries in two cases:

  • when you need to change the characteristics of a primitive type;
  • when you need to turn a field with a compound data type into a field with a single type.

Primitive data types include: number, string, date, boolean. Some of these data types have additional characteristics. Type Number has length and precision, type Line - length or unlimited.

Operator EXPRESS allows you to change not the data type, but additional characteristics. For example, he can turn a string with unlimited length into a string with limited length. This can be useful if you need to group query results by such a field. You can't group by fields with an unlimited length, so we convert it to a string with a length of 200 characters.

Request. Text= "CHOOSE
QUANTITY (DIFFERENT Arrival of Goods and Services. Link) AS Link
FROM
Document. Receipt of Goods and Services HOW Receipt of Goods and Services
GROUP BY
EXPRESS(Receipt of Goods and Services. Comment AS ROW (200))"
;

In some cases, queries to fields with a composite data type may not be processed optimally by the 1C platform. This results in longer query times, so it can be useful to convert a compound type to a single type in advance.

Request. Text= "CHOOSE
EXPRESS(Movement of GoodsTurnover.Order AS Document.Customer Order).Date AS Order Date,
Movement of GoodsTurnover.Nomenclature
FROM
RegisterAccumulations.Movement of Goods.Turnover AS Movement of GoodsTurnover
WHERE
Movement of GoodsTurnover.Order LINK Document.Client Order"
;

Operators CHOICE And IS NULL

Operator CHOICE similar to operator IF in the built-in 1C language, but has somewhat reduced functionality.

Let's say we want to receive contact information from the ContactInformation information register and, at the same time, indicate in a separate request field whether it belongs to a counterparty or an individual.

Request. Text= "CHOOSE
ContactInformation.Introduction,
CHOICE
WHEN VALUES TYPE(ContactInformation.Object) = TYPE(Directory.Counterparties)
THEN "
Counterparty "
ELSE CHOICE
WHEN VALUES TYPE(ContactInformation.Object) = TYPE(Directory.Individuals)
THEN "
Individual"
ELSE "Someone else" "
END
END AS OWNER
FROM
Register of Information. Contact Information AS Contact Information"
;

As can be seen from the example, in the design CHOICE there is always a condition after the word WHEN; value applied if the condition is true after the word THEN and the value applied if the condition is not met, after the word OTHERWISE. All three design elements CHOICE are mandatory. Omit element OTHERWISE, the same way as when using the operator IF in the built-in 1C language, it is impossible. Also from the operator CHOICE there is no analogue of the design ELSEIF, but you can invest one CHOICE in another, as was done in our example.

Operator IS NULL used in design CHOICE to compare a query field with type NULL.

Request. Text= "CHOOSE
CHOICE
WHEN THE VALUE IS NULL THEN 0
ELSE Meaning
END"
;

In addition, the operator IS NULL can be used in query conditions, such as in a sentence WHERE.

In the 1C:Enterprise query language, the function SUBSTRING() V format SUBSTRING(<Исходная строка>, <Начало>, <Длина>) can be applied to string data and allows you to select a fragment<Исходной строки>, starting with the character number<Начало>(characters in a line are numbered starting from 1) and length<Длина>characters. The result of the calculation of the SUBSTRING() function has a string type of variable length, and the length will be considered unlimited if<Исходная строка>has unlimited length and parameter<Длина>is not a constant or greater than 1024.

Calculation of the SUBSTRING() function on SQL server:
In the client-server version of the work, the SUBSTRING() function is implemented using the SUBSTRING() function of the corresponding SQL statement, passed to the SQL Server database server, which calculates the type of the result of the SUBSTRING() function using complex rules depending on the type and values ​​of its parameters, as well as depending on the context in which it is used.

In most cases, these rules do not affect the execution of a 1C:Enterprise query, however, there are cases when the maximum length of the result string calculated by SQL Server is essential for query execution. It is important to keep in mind that in some contexts when using the SUBSTRING() function, the maximum length of its result may be equal to the maximum length of a limited-length string, which in SQL Server is 4000 characters. This may cause the request to terminate unexpectedly.

For example, the request:
Code 1C v 8.x SELECT
CHOICE

ELSE NULL
THE END AS A Presentation,
CHOICE
WHEN Type = &LegalAddressIndividual
THEN SUBSTRING(Representation, 0, 200)
ELSE NULL
END AS Presentation1
FROM

SORT BY
Performance,
Performance1
terminates abnormally with the message DBMS error:
Microsoft OLE DB Provider for SQL Server: Warning: The query processor could not produce a query plan from the optimizer because the total length of all the columns in the GROUP BY or ORDER BY clause exceeds 8000 bytes.
HRESULT=80040E14, SQLSTATE=42000, native=8618

This occurs because Microsoft SQL Server calculates the maximum length of the string that results from the expression:
Code 1C v 8.x SELECTION
WHEN Type = &LegalAddressIndividual
THEN SUBSTRING(Representation, 0, 200)
ELSE NULL
THE END AS A Presentation,
equals 4000 characters. Therefore, the length of a record consisting of two such fields exceeds the 8000 bytes allowed for the sort operation.

Due to the described peculiarity of the execution of the SUBSTRING() function on SQL Server, using the SUBSTRING() function to convert strings of unlimited length to strings of limited length is not recommended. Instead, it is better to use the cast operator EXPRESS(). In particular, the above example can be rewritten as:
Code 1C v 8.x SELECT
CHOICE
WHEN Type = &LegalAddressIndividual
ELSE NULL
THE END AS A Presentation,
CHOICE
WHEN Type = &LegalAddressIndividual
THEN EXPRESS(Representation AS String(200))
ELSE NULL
END AS Presentation1
FROM
Register of Information. Contact Information HOW Contact Information
SORT BY
Performance,
Performance1