Creating and working with requests (for beginners). Creating and working with requests (for beginners) 1s 8.3 if in a request

1C programming consists of more than just writing a program. 1C is an ingot of user actions and data with which he works.

The data is stored in a database. 1C queries are a way to retrieve data from a database in order to show it to the user in a form or to process it.

The fundamental part of the report is the 1C request. In the case of a report, the ACS is the largest part of the report.

Sit down. Take a breath. Calm down. Now I will tell you the news.

To program in 1C, it is not enough to know the 1C programming language. You also need to know the 1C query language.

The 1C query language is a completely separate language that allows us to specify what data we need to get from the database.

He is also bilingual - that is, you can write in Russian or English. It is extremely similar to the SQL query language and those who know it can relax.

How 1C Requests are used

When a user launches 1C in Enterprise mode, there is not a single gram of data in the running client. Therefore, when you need to open a directory, 1C requests data from the database, that is, it makes a 1C request.

1C queries are:

  • Automatic queries 1C
    Generated automatically by the system. You have created a document list form. Added a column. This means that when you open this form in Enterprise mode, there will be a query and the data for this column will be requested.
  • Semi-automatic queries 1C
    There are many methods (functions) in the 1C language, when accessed, a query is made to the database. For example.GetObject()
  • Manual 1C queries (written by the programmer specifically as a query)
    You can write a 1C request yourself in code and execute it.

Creating and executing 1C queries

A 1C request is the actual text of the request in the 1C request language.
The text can be written with pens. That is, take it and write it (if you know this language).

Since 1C promotes the concept of visual programming, where much or almost everything can be done without writing code by hand, there is a special Query Constructor object that allows you to draw the text of a query without knowing the query language. However, miracles do not happen - for this you need to know how to work with the constructor.

Once the text of the 1C request is ready, it needs to be executed. For this purpose there is an object in the 1C code Request(). Here's an example:

Request = New Request();
Query.Text = "SELECT
| Nomenclature.Link
|FROM
| Directory.Nomenclature AS Nomenclature
|WHERE
| Nomenclature.Service";
Select = Query.Run().Select();

Report(Selection.Link);
EndCycle;

As you can see in the example, after executing the 1C request, the result comes to us and we must process it. The result is one or several rows of the table (in a special form).

The result can be uploaded to a regular table:
Fetch = Query.Run().Unload(); //Result – table of values

Or just go around line by line.
Select = Query.Run().Select();
While Select.Next() Loop
//Do something with the query results
EndCycle;

Working with 1C requests

Basic principles of 1C queries

Basic principles of constructing a 1C request –
SELECT List of Fields FROM Table Title WHERE Conditions

An example of constructing such a 1C request:

CHOOSE
//list of fields to select
Link,
Name,
Code
FROM
//name of the table from which we select data
//list of tables is a list of objects in the configurator window
Directory.Nomenclature
WHERE
//indicate selection
Product Type = &Service //selection by external value
Or Service // “Service” attribute of type Boolean, selection by value True
SORT BY
//Sorting
Name

List of 1C tables

You can see the table names in the configurator window. You just need to write “Directory” instead of “Directories”, for example “Directory.Nomenclature” or “Document.Sales of Goods and Services” or “Register of Accumulation.Sales”.

There are additional tables (virtual) for registers that allow you to get the final numbers.

Information Register.RegisterName.Last Slice(&Date) – 1C request from the information register, if it is periodic, for a specific date

Accumulation Register.Register Name.Balances(&Date) – 1C request from the register of balances for a specific date

Accumulation Register.Register Name.Turnover (&Start Date, &End Date) – 1C request from the turnover register for the period from the start date to the end date.

Additional principles

When we request a list of some data, the basic principles work. But we can also request numbers and the request can count them for us (add them, for example).

CHOOSE
//Quantity(FieldName) – counts the quantity
//Field AS OtherName – renames the field
Quantity (Link) AS Quantity of Documents Posted
FROM

WHERE
Conducted

This 1C request will return us the total number of documents. However, every document has an Organization field. Let’s say we want to count the number of documents for each organization using a 1C query.

CHOOSE
//just a document field
Organization,
//count the quantity
Quantity(Link) AS QuantityBy Organizations
FROM
Document. Sales of Goods and Services
WHERE
Conducted
GROUP BY

Organization

This 1C request will return us the number of documents for each organization (also called “by organization”).

Let us additionally calculate the amount of these documents using a 1C request:

CHOOSE
//just a document field
Organization,
//count the quantity

//count the amount

FROM
Document. Sales of Goods and Services
WHERE
Conducted
GROUP BY
//must be used if the list of fields has a count() function and one or more fields at the same time - then you need to group by these fields
Organization

This 1C request will also return the amount of documents to us.

CHOOSE
//just a document field
Organization,
//count the quantity
Quantity(Link) AS QuantityBy Organizations,
//count the amount
Amount(DocumentAmount) AS Amount
FROM
Document. Sales of Goods and Services
WHERE
Conducted
GROUP BY
//must be used if the list of fields has a count() function and one or more fields at the same time - then you need to group by these fields
Organization
PO RESULTS General

The 1C query language is extensive and complex, and we will not consider all its capabilities in one lesson - read our next lessons.

Briefly about the additional features of the 1C query language:

  • Joining data from multiple tables
  • Nested Queries
  • Batch request
  • Creating your own virtual tables
  • Query from value table
  • Using built-in functions for getting and manipulating values.

1C Query Builder

In order not to write the request text by hand, there is a 1C request designer. Just right-click anywhere in the module and select 1C Query Designer.

Select the desired table on the left in the 1C query designer and drag it to the right.

Select the required fields from the table in the 1C query designer and drag to the right. If you would like not only to select a field, but to apply some kind of summation function to it, after dragging, click on the field twice with the mouse. On the Grouping tab, you will then need to select (drag) the required fields for grouping.

On the Conditions tab in the 1C query designer, you can select the necessary selections in the same way (by dragging the fields by which you will make the selection). Be sure to select the correct condition.

On the Order tab, sorting is indicated. On the Results tab – summing up the results.

Using the 1C query designer, you can study any existing query. To do this, right-click on the text of an existing request and also select 1C query designer - and the request will be opened in the 1C query designer.

The 1C 8 query language is an indispensable tool for a 1C programmer; it allows you to write more concise, simple, understandable code, and use fewer system resources when working with data. This article opens a series of lessons dedicated to the 1C 8 query language. In the first lesson we will look at the structure of the main operator of this language - CHOOSE. Using this operator, you can create selections from database tables. Selected table data can be sorted, conditions placed on it, linked and combined with data from other tables, grouped by various fields, and much more.

Query language 1C enterprise 8 - Operator structure SELECT

Let's look at the structure of the SELECT operator (optional parts of the operator are indicated in square brackets). The 1C query language provides a wide range of tools for creating data samples.

SELECT [ALLOWED] [DIFFERENT] [FIRST A] [Field1] [AS Alias1], [Field2] [AS Alias2], ... [FieldM] [AS AliasB] [PUT TemporaryTableName] [FROM Table1 AS AliasTableTable1 [[INNER JOIN ][LEFT JOIN][FULL JOIN] Table2 AS Alias ​​Table2 [[INNER JOIN][LEFT JOIN][FULL JOIN] TableC AS Alias ​​TablesC BY Expression1 [And Expression2]...[And ExpressionD]] ... ... BY Expression1 [And Expression2]...[And ExpressionE]] ... [TableF AS TableF Alias] ... ] [GROUP BY GroupingField1[,] ... [GroupingFieldG]] [WHERE Expression1 [AND Expression2] ... [AND ExpressionH]] [UNITE ALL...] [; ...] [INDEX BY Alias1 ... AliasB] [TOTALS [AggregationFunction(Field1)][,] [AggregationFunction(Field2)][,] ... [AggregationFunction(FieldI)] BY [GENERAL][,] [ GroupingField1][,] ... [GroupingFieldj]]

Keywords and blocks for working with fields

  • CHOOSE— a keyword indicating the beginning of the operator;
  • ALLOWED indicates that the selection should include table records that have read access for the given user;
  • VARIOUS indicates that the sample should include only different (across all fields) flows. In other words, duplicate rows will be excluded from the sample;
  • FIRST A if you specify this keyword, then only the first A of the rows selected by the query will be included in the selection, where A is a natural number;
  • Field block— this block indicates the fields that need to be included in the selection. These fields will be selected columns. In the simplest case, the field looks like this: Table Alias.TableFieldName AS Field Alias

    This way we indicate which table we are taking this field from. The 1C query language allows you to specify any aliases, but they should not be repeated in the same SELECT statement. A field can be more complex, consisting of various combinations of table fields, query language functions, and aggregate functions, but we won't cover those cases in this tutorial;

Keywords and blocks for working with tables

  • PUT TemporaryTableName- keyword PLACE is intended to create a temporary table with a specific name, which will be stored in RAM in a given 1C 8 session until it ends or until the temporary table is destroyed. It should be noted that the names of temporary tables in one 1C 8 session should not be repeated;
  • Block of tables and relationships— the block indicates all the tables used in this query, as well as the relationships between them. The block begins with a keyword FROM, followed by the name and alias of the first table. If this table is related to other tables, then the relationships are indicated. The 1C query language contains the following set of connection types:
    • INNER JOIN— a record from the left table will be included in the selection only if the connection condition is met, a record from the right table will be included in the selection only if the connection condition is met;
    • LEFT CONNECTION— a record from the left table will be included in the selection in any case, a record from the right table will be included in the selection only if the connection condition is met;
    • FULL CONNECTION— a record from the left table will be included in the selection first in any case, then only if the connection condition is met, a record from the right table will be included in the selection first in any case, then only if the connection condition is met. In this case, the resulting duplicate rows are excluded from the sample.

    After the connection type, the name and alias of the second table are indicated. Next comes the keyword BY, followed by communication conditions connected with each other by logical operators AND, OR. Each expression in the condition must return a Boolean value (True, False). If the first table is connected to some tables other than the second, then the connection type is again indicated, and so on. Each of the tables participating in the connection, in turn, can be connected to other tables, this is shown in the query structure diagram. If the table is not related to the first one, then it is indicated without a connection type, then its connections may follow, and so on;

Keywords and data conversion blocks

  • Group block— this block is used to group table rows. Rows are combined into one if the values ​​of the fields specified after the keyword GROUP BY turn out to be the same. In this case, all other fields are summed, averaged, maximized, or minimized using aggregate functions. Aggregate functions are used in a field block. Example: Maximum(TableAlias.TableFieldName) AS FieldAlias
  • Condition block- in this block after the keyword WHERE conditional expressions separated by logical operators are indicated AND, OR, in order for any of the selected rows to be included in the sample, it is necessary that all conditions in the aggregate have a value True.
  • COMBINE EVERYTHING— this keyword is used to combine queries (operators CHOOSE). The 1C query language allows you to combine several queries into one. In order for queries to be merged, they must have the same set of fields;
  • «;» - semicolons are used to separate statements that are independent of each other CHOOSE;
  • INDEX BY— the keyword is used to index the fields specified after it;
  • Summary block— used to build tree-like samples. For each of the grouping fields specified after the keyword BY, a separate row will be created in the selection. In this line, using aggregate functions, the total values ​​of the fields specified after the keyword will be calculated RESULTS.

Do you want to continue learning the 1C 8 query language? Then read the next article.

Request . Text = "CHOOSE | StorageUnits.Link |FROM | Directory.usStorageUnits HOW touseStorageUnits // Example 1: comparison with an empty boolean value: |WHERE | StorageUnits.AllowSelectionFromReserveZone = False // Example 2. but if this Boolean is defined, then it’s better like this: // condition for a negative Boolean: |WHERE | NOT Storage Units. Allow Selection From Reserve Zone // Example 3. selection based on the condition of an empty field that has the type “directory of a specific type” |WHERE | StorageUnits.ActiveSelectionArea = VALUE(Directory.usSelectionArea.EmptyRef) // Example 3a. selection based on the condition of an empty field having the type “document of a specific type” |WHERE | OurInformationRegister.Document = VALUE(Document.OurDocument.EmptyLink) // Example 3b. selection based on the condition of an empty field having the type “documents of different types” ( composite field) |WHERE | (OurInformationRegister.Document = VALUE(Document.OurDocument1.EmptyLink) | OR OurInformationRegister.Document = VALUE(Document.OurDocument2.EmptyLink) | OR... (etc. - we sequentially list the conditions for all possible types of this composite field) ) // Example 4. or vice versa, if you need to select a filled value of the "string" type, then the condition will help: |WHERE | Storage Unit.Name > """" // Example 5. if you need to select documents of a specific type, with a composite data type, for example, in the "RunningTasks" register, the "Task" resource has a composite type, among the values ​​of which the document "Selection" is possible |WHERE | EXPRESS(Information RegisterExecutedTasks.Task AS Document.Selection) LINK Document.Selection // Example 5a. Another similar example when you need to select documents of a specific type | CHOICE | WHEN TO EXPRESS (ag Correspondence of Documents. DocumentBU AS Document. Receipt of Goods and Services) LINK Document. Receipt of Goods and Services | THEN ""Receipt of Goods and Services"" | WHEN TO EXPRESS (ag Correspondence of Documents. DocumentBU AS Document. Sales of Goods and Services) LINK Document. Sales of Goods and Services | THEN ""Sales of Goods and Services"" | ELSE """" | END AS Document View // Example 6. selection by condition of an undefined value: |WHERE | SavedSettings.User = UNDEFINED // Example 7. selection by type of movement "Incoming" of the accumulation register, "Expense" - similarly): |WHERE | RegProductsInRetail.MovementType = VALUE(MovementTypeAccumulation.Incoming) // Example 8. How to indicate in a request that there is no need to execute the request (for example, you need to programmatically, depending on some condition, return an empty request result - Request.Text = StrReplace(Request.Text, "WHERE Doc.Link = &DocumentLink" , "WHERE IS THE LIE");). To do this, just add the condition “Where is False”. By the way, regardless of the volume of data requested in the sample, such a request will be executed instantly. |WHERE IS THE LIE // Example 9. Checking that the query result contains data: If notRequest.Execute().Empty() Then // Example 10. selection based on an empty date: |WHERE | tbStrings.CancellationDate = DATETIME(1, 1, 1)

In this article we want to discuss everything with you 1C query language functions, and query language constructs. What is the difference between function and design? The function is called with parentheses and possible parameters in them, and the construct is written without parentheses. Undoubtedly all structures and functions of the 1C query language make the data acquisition process flexible and multifunctional. These functions and constructs apply to request fields, and some also apply to conditions.

1C Query Language Functions

Because a clear description 1C query language functions is much less common than descriptions of structures, we decided to start looking at functions. Now let's look at each one separately, describing its purpose, syntax and example of use, so:

1. Function DATE TIME- this function creates a constant field with the "Date" type.

Syntax: DATE TIME(<Год>,<Месяц>,<День>,<Час>,<Минута>,<Секунда>)

Usage example:

2. DATE DIFFERENCE function- returns the difference between two dates in one of the dimensions (year, month, day, hour, minute, second). The measurement is passed as a parameter.

Syntax: DIFFERENCEDATE(<Дата1>, <Дата2>, <Тип>)

Usage example:

Query.Text = "SELECT | DIFFERENCEDATE(DATETIME(2015, 4, 17), DATETIME(2015, 2, 1), DAY) | AS Qty.Days";

3. Function VALUE- sets a constant field with a predefined record from the database; you can also get an empty link of any type.

Syntax: VALUE(<Имя>)

Usage example:

Request.Text = "SELECT //predefined element | VALUE(Directory.Currencies.Dollar) AS Dollar, //empty link | VALUE(Document.Receipt of Goods and Services.EmptyLink) AS Receipt, //transfer value | VALUE(Transfer. Legal Individual. Individual) AS Individual, //predefined account | VALUE(Chart of Accounts. Self-supporting. Materials) AS Account_10" ;

4. SELECT function- we have before us an analogue of the IF construction, which is used in the code, only this one is used in 1C queries.

Syntax: CHOICE WHEN<Выражение>THEN<Выражение>OTHERWISE<Выражение>END

Usage example:

Request.Text = //if the amount is more than 7500, then there should be a discount of 300 rubles, //so if the condition is triggered then the function //returns Sum - 300 //otherwise the request will return simply Sum "SELECT | SELECT | WHEN TCReceipts.Amount > 7500 | THEN TCReceipts.Amount - 300 | ELSE TCReceipts.Amount | END AS AmountWithDiscount |FROM | Document.Receipt of GoodsServices.Goods AS TCReceipts";

5. EXPRESS function- allows you to express a constant field with a specific type.

Syntax: EXPRESS(FieldName AS TypeName)

Usage example:

Query.Text = "SELECT VARIOUS | Sales.Registrar.Number, | SELECT | WHEN Sales.Registrar LINK Document.Consumable | THEN EXPRESS(Sales.Registrar AS Document.Consumable) | ELSE SELECT | WHEN Sales.Registrar LINK Document.Implementation | THEN EXPRESS(Sales.Registrar AS Document.Implementation) | END | ... | END AS Number | FROM | RegisterAccumulations.Purchases AS Purchases";

Is there another option for using the EXPRESS function in fields of mixed types, where do they occur? The simplest example is the “Registrar” for any register. So why might we need to qualify the type in the registrar? Let's consider the situation when we select the "Number" field from the registrar, from which table will the number be selected? The correct answer of all! Therefore, for our query to work quickly, we should specify an explicit type using the EXPRESS function

Usage example:

Query.Text = "SELECT | EXPRESS(Nomenclature.Comment AS Line(300)) AS Comment, | EXPRESS(Nomenclature.Sum AS Number(15,2)) AS Sum |FROM | Directory.Nomenclature AS Nomenclature";

6. ISNULL function(alternative spelling ISNULL) - if the field is of type NULL, then it is replaced with the second parameter of the function.

Syntax: ISNULL(<Поле>, <ПодставляемоеЗначение>)

Usage example:

Also note that it is advisable to ALWAYS replace the NULL type with some value, because comparison with type NULL always returns FALSE even if you compare NULL with NULL. Most often, NULL values ​​are formed as a result of joining tables (all types of joins except internal ones).

Query.Text = //Select the entire item and its balances //if there is no balance in some item, then there will be a field //NULL which will be replaced with the value 0 "SELECT | No. Link, | ISNULL(ProductsInStockRemains.InStockRemaining, 0) AS Remainder | FROM | Directory.Nomenclature AS No. | LEFT CONNECTION Register Accumulations. GoodsInWarehouses. Remainings AS GoodsInWarehousesRemains | ON (GoodsInWarehousesRemains. Nomenclature = No. Link)";

7. REPRESENTATION function- allows you to get a representation of the request field.

Syntax: PERFORMANCE(<НаименованиеПоля>)

Usage example:

Query.Text = "SELECT | REPRESENTATION(FreeRemainingRemains.Nomenclature) AS Nomenclature, | REPRESENTATION(FreeRemainingRemaining.Warehouse) AS Warehouse, | FreeRemainingRemaining.InStockRemaining |FROM |Accumulation Register.FreeRemaining.Remaining AS FreeRemainingRemaining";

Constructs in the 1C query language

We discussed with you above 1C query language functions, now it's time to consider constructs in the 1C query language, they are no less important and useful, let’s get started.

1. Construction LINK- is a logical operator for checking a reference type. Most often encountered when checking a field of a complex type against a specific type. Syntax: LINK<Имя таблицы>

Usage example:

Request.Text = //if the recorder value type is document Receipt, //then the query will return "Receipt of goods", otherwise "Sales of goods" "SELECT | SELECT | WHEN Remainings.Registrar LINK Document.Receipt of Goods and Services | THEN ""Receipt"" | ELSE ""Consumption"" | END AS Type of Movement | FROM | Accumulation Register. Remaining Products in Warehouses AS Remains" ;

2. Design BETWEEN- this operator checks whether the value is within the specified range.

Syntax: BETWEEN<Выражение>AND<Выражение>

Usage example:

Request.Text = //get the entire nomenclature whose code is in the range from 1 to 100 "SELECT | Nomenclature.Link |FROM | Directory.Nomenclature AS Nomenclature |WHERE | Nomenclature.Code BETWEEN 1 AND 100" ;

3. Construction B and B HIERARCHY- check whether the value is in the transferred list (arrays, tables of values, etc. can be transferred as a list). The IN HIERARCHY operator allows you to view the hierarchy (an example of using the Chart of Accounts).

Syntax: IN(<СписокЗначений>), IN HIERARCHY(<СписокЗначений>)

Usage example:

Request.Text = //select all subaccounts of the account "SELECT | Self-supporting. Link AS Account | FROM | Chart of Accounts. Self-supporting AS Self-supporting | WHERE | Self-supporting. Link IN HIERARCHY VALUE (Chart of Accounts. Self-supporting. Goods)";

4. Design SIMILAR- This function allows us to compare a string with a string pattern.

Syntax: LIKE "<ТекстШаблона>"

Row pattern options:

% - a sequence containing any number of arbitrary characters.

One arbitrary character.

[...] - any single character or sequence of characters listed inside square brackets. The enumeration can specify ranges, for example a-z, meaning an arbitrary character included in the range, including the ends of the range.

[^...] - any single character or sequence of characters listed inside square brackets except those listed after the negation sign.

Usage example:

Query.Text = //find the entire nomenclature that contains the root TABUR and begins //either with a small or capital letter t "SELECT | Nomenclature. Link | FROM | Directory. Nomenclature AS Nomenclature | WHERE | Products. Name LIKE "" [Tt ]abur%""" ;

5. Design ALLOWED- this operator allows you to select only those records from the database for which the caller has read permission. These rights are configured at the record level (RLS).

Syntax: ALLOWED is written after the keyword SELECT

Usage example:

Request.Text = "SELECT ALLOWED | Counterparties. Link | FROM | Directory. Counterparties AS Counterparties";

6. Design VARIOUS- allows you to select records in which there are no duplicate records.

Syntax: VARIOUS is written after the keyword SELECT

Usage example:

Request.Text = //selects records to which the reader has rights "SELECT VARIOUS | Counterparties.Name |FROM | Directory. Counterparties AS Counterparties" ;

Also, the VARIOUS construction can be used with the ALLOWED operator and other operators.

Usage example:

Request.Text = //selects various records to which the reader has rights "SELECT ALLOWED VARIOUS | Counterparties.Name |FROM | Directory. Counterparties AS Counterparties";

7. Design FIRST- selects the number of records specified in the parameter from the query result.

Syntax: FIRST<число>

Usage example:

Request.Text = //select the first 4 CCD numbers from the directory "SELECT FIRST 4 | CCD Numbers. Link | FROM | Directory. CCD Numbers AS CCD Numbers";

8. Design FOR CHANGE- allows you to lock a table, works only in transactions (relevant only for automatic locks).

Syntax: FOR CHANGE<НаименованиеТаблицы>

Usage example:

Query.Text = "SELECT | Free Remainings Remainings. Nomenclature, | Free Remainings Remainings. Warehouse, | Free Remainings Remainings. In Stock Remaining | FROM | Register of Accumulations. Free Remainings. Remainings AS Free Remainings Remainings | FOR CHANGE | Register of Accumulations. Free Remainings. Remainings";

9. Design ORDER BY- organizes data by a specific field. If the field is a link, then when setting the flag AUTO ORDER Sorting will occur by link representation; if the flag is turned off, then links are sorted by the seniority of the link address in memory.

Syntax: SORT BY<НаименованиеПоля>AUTO ORDER

Usage example:

Query.Text = "SELECT | Free Remainings Remainings. Nomenclature AS Nomenclature, | Free Remainings Remainings. Warehouse AS Warehouse, | Free Remainings Remainings. In Stock Remaining | FROM | Register Accumulations. Free Remainings. Remaining AS Free Remaining Remainings | | ORDER BY | Nomenclature | AUTO ORDER RECOVERY";

10. Design GROUP BY- used to group query strings by specific fields. Numeric fields must be used with any aggregate function.

Syntax: GROUP BY<НаименованиеПоля1>, .... , <НаименованиеПоляN>

Usage example:

Query.Text = "SELECT | ProductsInWarehouses.Nomenclature AS Nomenclature, | ProductsInWarehouses.Warehouse, | SUM(GoodsInWarehouses.InStock) AS INSTOCK |FROM | RegisterAccumulations.ProductsInWarehouses AS ProductsInWarehouses | |GROUP BY | ProductsInWarehouses.Nomenclature, | ProductsIn Warehouses.Warehouse";

11. Design HAVING- allows you to apply an aggregate function to a data selection condition, similar to the WHERE construction.

Syntax: HAVING<агрегатная функция с условием>

Usage example:

Query.Text = //selects grouped records where the InStock field is greater than 3 "SELECT | ItemsInStocks.Nomenclature AS Nomenclature, | ItemsInWarehouses.Warehouse, | SUM(ItemsInStocks.InStock) AS INSTOCK |FROM | RegisterAccumulations.ItemsInStocks AS ItemsInStocks | |GROUP BY | ProductsInWarehouses.Nomenclature, | ProductsInWarehouses.Warehouse | |AVAILABLE | AMOUNT(ProductsInWarehouses.InStock) > 3" ;

12. Construction INDEX BY- used for indexing the query field. A query with indexing takes longer to complete, but speeds up searching through indexed fields. Can only be used in virtual tables.

Syntax: INDEX BY<Поле1, ... , ПолеN>

Usage example:

Query.Text = "SELECT | Ts.NameOS, | Ts.FolderNumber, | Ts.CodeOS, | Ts.Term, | Ts.Type | PLACE DataTs | FROM | &Ts AS Ts | | INDEX BY | Ts.NameOS, | Ts .CodeOS";

13. Design WHERE- allows you to impose a condition on any selection fields. The result will include only records that satisfy the condition.

Syntax: WHERE<Условие1 ОператорЛогСоединения УсловиеN>

Usage example:

Query.Text = //all records with CompensationRemaining are selected<>0 and //AmountForCalcCompRemaining > 100 "SELECT | CompensationRPORemains.Counterparty, |CompensationRPORemains.Child, | CompensationRPORemains.CompensationRemaining, | CompensationRPORemains.AmountForCalcCompRemains |Place DataTz |FROM | Accumulation Register.CompensationRP.Remains AS CompensationRPOstat ki |WHERE |CompensationRPORemaining.CompensationRemaining<>0 | And CompensationRPORemains.AmountForCalcCompRemaining> 100" ;

14. Design RESULTS... GENERAL- used to calculate totals; the design specifies the fields by which totals will be calculated and aggregate functions applied to the total fields. When using totals for each field following the TOTAL construction, data is grouped. There is an optional GENERAL construct; its use also provides additional grouping. You will see an example of the request result below.

Syntax: RESULTS<АгрегатнаяФункция1, ... , АгрегатнаяФункцияN>BY<ОБЩИЕ> <Поле1, ... , ПолеN>

Usage example:

Request.Text = "SELECT | Calculations. Counterparty Agreement. Type of Agreement AS Contract Type, | Calculations. Counterparty Agreement AS Contract, | Calculations. Counterparty, | Calculations. Amount of Mutual Settlement Balance AS Balance | FROM | Register of Accumulations. Mutual Settlement WITH Counterparties. Balances AS Calculations | TOTAL | AMOUNT (Balance) |Software | GENERAL, | Type of Agreement";

The figure outlines the groupings that were formed during the execution of the request, the top one refers to the GENERAL section, and the second to the Counterparty AgreementAgreement Type field.

In this article we will examine the topic of nested tables in the 1C query language.

You can use a nested query source table in query select fields. For example, the document “Provision of services” has a tabular part of Services, and so, this tabular part can also be displayed in the selection field. Now you will see how this can be implemented.

In my training database, I will launch the query console, open the query designer and select the “Provision of Services” table.

Let's expand this table

And in it we see the tabular part “Services”.

Let's select this entire table part.

As you can see, the entire tabular part of the service has completely gone into the fields.

Please note that the tabular part, in fact, comes as a separate field called “Services” and the type of which will be “Request Result”. Let's learn how to use a nested table in a query.

Let's leave three fields of the nested table and add some fields from the document header.

Let's click OK in the designer and see what our request will look like.

As you can see, in the request there is a dot after the “Services” field, and the selected fields are listed in brackets after it.

Let's fulfill the request.

In the figure we see that all selected fields in the tabular part of the document are listed separated by commas in the “Services” field. Not all query consoles have a display like the one in the figure above; sometimes it may just say “ “.

Another interesting point: in a nested table you can put an asterisk instead of fields, then all the fields of the tabular part will appear. This cannot be done in the constructor, only manually in the request. The request will take the following form:

Let's see how such a request will be executed.

The only thing is that this asterisk will not be saved if we open the query constructor.

We have learned how to make a query with a nested table in the console, now we will learn how to use a nested table in a selection

In reality, it is not that difficult to access a nested table when processing a query. You simply access the selection by the name of your table, and get a variable with the “Query Result” type. And then you process it as a normal request result: if you want, get a sample, if you want, do an upload.

Below is a small example of code that works with a nested table:


&On server
Procedure FillOnServer()
Request = New Request;
Request. Text = "CHOOSE
| Sale of Product. Link,
| Sale of Product.Products.(
| Product,
| Quantity
|FROM
| Document. Selling Products HOW TO Selling Products"
;
Fetch = Query. Run(). Choose();
Bye Selection. Next() Loop
TopLine of the Tree = Sale of Products. GetItems();
NewRow = TopRowTree. Add();
New line. Link = Selection. Link;
TableProducts = Selection. Goods;
SelectionProducts = TableProducts. Choose();
While Selection of Products. Next() Loop
TreeChildRow = NewRow. GetItems();
ProductRow = ChildTreeRow. Add();
ProductString. Link = Product Selection. Product;
ProductString. Quantity = SampleItems. Quantity ;
EndCycle;
EndCycle;
End of Procedure

Let me explain the above code.

First of all, we got a linear selection, and we go through this selection in a loop, in which we create the top line of the value tree (it is on the form), and write a link to our document in it.

And then the most interesting thing, you can even look at it later in the debugger yourself, we turn to the Products selection field, and for convenience, write this field into a separate variable in the TableProducts. This variable is of the “Query Result” type. And you can easily get a sample of this result. That's what we do. It remains to bypass this selection using the next function and the while loop.

And inside this loop we will refer to the selection fields as fields of a nested table, and write them to the child rows of the tree from the form.

This is the result this code will return

Still have questions?

You will answer them yourself when you study my course “Queries in 1C for Beginners”. Where these and many other issues are discussed in more detail. All information is given in a simple and accessible form and is understandable even to those who are not particularly familiar with programming in 1C.

Promo code for 20% discount: hrW0rl9Nnx

Support my project by donating any amount

Join my groups.