Как добавить новые строки в sql
Перейти к содержимому

Как добавить новые строки в sql

  • автор:

Добавление строк в таблицы SQL

Как правильно добавить строку в таблицу SQL если есть вторая таблица связанная с первой по полю с Auto_incrimetn при попытке добавления запросом пишет ошибку Cannot add or update a child row: a foreign key constraint fails ( test_app . tests_iq_question , CONSTRAINT tests_iq_question_ibfk_1 FOREIGN KEY ( question_id ) REFERENCES tests_iq_answers ( Id_question ))

Отслеживать

задан 6 апр 2014 в 10:11

@валах вероятно, вы пытаетесь добавить в первую таблицу запись с внешним ключом, которого нет во второй таблице

Как добавить новые строки в таблицу в SQL

В SQL (Structured Query Language) есть возможность добавлять новые строки в таблицу с помощью оператора INSERT. Это позволяет вам добавлять данные в уже существующую таблицу, расширяя ее содержимое. В этой статье мы рассмотрим различные способы добавления новых строк в таблицу в SQL.

Использование оператора INSERT

Оператор INSERT в SQL используется для добавления новых строк в таблицу. Он имеет следующий синтаксис:

 INSERT INTO table_name (column1, column2, column3, . ) VALUES (value1, value2, value3, . ); 

table_name — название таблицы, в которую вы хотите добавить новые строки.

column1, column2, column3, . — имена столбцов таблицы, в которые вы хотите добавить значения. Вы можете указать только те столбцы, которые хотите заполнить значениями, остальные будут иметь значения NULL или значения по умолчанию, если они определены.

value1, value2, value3, . — значения, которые вы хотите добавить в таблицу. Они должны соответствовать типам данных столбцов.

Пример 1:

Добавление новой строки в таблицу «users», имеющую столбцы «id», «name» и «age»:

 INSERT INTO users (id, name, age) VALUES (1, 'John Doe', 25); 

Добавление нескольких строк одновременно

Вы также можете добавить несколько строк одновременно, используя один оператор INSERT. Для этого вы должны указать несколько наборов значений, разделенных запятыми:

 INSERT INTO table_name (column1, column2, column3, . ) VALUES (value1, value2, value3, . ), (value1, value2, value3, . ), (value1, value2, value3, . ); 

Пример 2:

Добавление двух новых строк в таблицу «users»:

 INSERT INTO users (id, name, age) VALUES (2, 'Jane Smith', 30), (3, 'Mike Johnson', 35); 

Добавление значений из другой таблицы

В SQL также есть возможность добавлять значения в таблицу из другой таблицы. Для этого вы можете использовать подзапрос в операторе INSERT:

 INSERT INTO table_name (column1, column2, column3, . ) SELECT column1, column2, column3, . FROM other_table WHERE condition; 

other_table — название таблицы, из которой вы хотите добавить значения.

condition — условие, которому должны соответствовать строки из other_table, чтобы быть добавленными в table_name.

Пример 3:

Добавление всех строк из таблицы «employees» в таблицу «users», где возраст сотрудников больше 30:

 INSERT INTO users (id, name, age) SELECT id, name, age FROM employees WHERE age > 30; 

Использование DEFAULT для автоматического заполнения значений

Если у вас есть столбцы с значениями по умолчанию в таблице, вы можете использовать ключевое слово DEFAULT в операторе INSERT, чтобы автоматически заполнить эти значения:

 INSERT INTO table_name (column1, column2, column3, . ) VALUES (value1, DEFAULT, value3, . ); 

В этом случае значение по умолчанию для column2 будет использовано.

Пример 4:

Добавление новой строки в таблицу «users», где значение столбца «age» будет использовано значение по умолчанию:

 INSERT INTO users (id, name, age) VALUES (4, 'Anna Johnson', DEFAULT); 

Заключение

В этой статье мы рассмотрели различные способы добавления новых строк в таблицу в SQL с использованием оператора INSERT. Вы можете добавлять одну или несколько строк одновременно, а также использовать значения из других таблиц или значения по умолчанию. Обратите внимание, что при добавлении новых строк в таблицу важно учитывать типы данных столбцов и условия, которым должны соответствовать добавляемые значения.

Как добавить новые строки в sql

Insert Into SQL – How to Insert Into a Table Query [Example Statement]

Insert Into SQL – How to Insert Into a Table Query [Example Statement]

If you want to add data to your SQL table, then you can use the INSERT statement.

In this article, I will show you how to use the INSERT statement to add a single row, multiple rows, and to copy rows from one SQL table to another.

Basic INSERT syntax

Here is the basic syntax for adding rows to a table in SQL:

The first line of code uses the INSERT statement followed by the name of the table you want to add the data to. After the table name, you should specify the column names.

The second line of code is where you will add the values for the rows. It is important that the number of values matches with the number of columns specified or else you will get an error message.

How to add a row to a SQL table

In this example we have a table called dogs with the columns of id , name and gender . We want to add one dog called AXEL .

This is what the code looks like to add AXEL to the table:

This is what the table looks like.

Screen-Shot-2021-10-06-at-5.19.41-AM

What happens if the number of values does not match the columns?

As mentioned earlier, the number of columns has to match with the number of values.

If I alter the code to remove a value, then I would get an error message.

Screen-Shot-2021-10-06-at-5.22.25-AM

Since we specified 3 columns, we need to provide three values for each row added to the table.

What happens if you ignore column constraints?

When you create SQL tables, you will add column constraints which serve as rules for the column.

In our dogs table, the name and gender columns have a constraint of NOT NULL . This rule means that a value cannot be absent from the row.

When I try to add NULL for the gender , I come back with an error message.

Screen-Shot-2021-10-06-at-5.46.44-AM

Any constraints that you specified in the creation of your SQL table need to be respected when adding rows.

How to add multiple rows to a table in SQL

If you want to add multiple rows to a table all at once, then you can use this syntax:

It is important to remember the commas between each of the rows or else you will get an error message.

Screen-Shot-2021-10-06-at-5.58.22-AM

This is what the code would look like to add eight dogs to the table all at once:

This is what the table looks like now:

Screen-Shot-2021-10-06-at-6.00.14-AM

How to copy rows from one table and insert them into another table

You can use the SELECT and INSERT statements to copy rows from one SQL table to another.

This is the basic syntax:

In this example, I have created a cats table with three rows in it with the same column names as the dogs table.

Screen-Shot-2021-10-06-at-6.26.46-AM

We can add all of the cats data into the dogs table using the following code:

This is what the new dogs table looks like with the additional cats :

Screen-Shot-2021-10-06-at-6.27.43-AM

Conclusion

If you want to add data to your SQL table, then you can use the INSERT statement.

Here is the basic syntax for adding rows to your SQL table:

The second line of code is where you will add the values for the rows. It is important that the number of values matches with the number of columns specified or else you will get an error message.

When you try to ignore column constraints in adding rows to the table, then you will receive an error message.

If you want to add multiple rows to a table all at once, then you can use this syntax:

You can use the SELECT and INSERT statement to copy rows from one SQL table to another.

SQL INSERT

Summary: in this tutorial, you will learn how to insert data into a table using the SQL INSERT statement.

Introduction to the SQL INSERT statement

SQL provides the INSERT statement that allows you to insert one or more rows into a table. The INSERT statement allows you to:

  1. Insert a single row into a table
  2. Insert multiple rows into a table
  3. Copy rows from a table to another table.

We will examine each function of the INSERT statement in the following sections.

Insert one row into a table

To insert one row into a table, you use the following syntax of the INSERT statement.

There are some points that you should pay attention to when you insert a new row into a table:

  • First, the number of values must be the same as the number of columns. In addition, the columns and values must be the correspondent because the database system will match them by their relative positions in the lists.
  • Second, before adding a new row, the database system checks for all integrity constraints e.g., foreign key constraint, primary key constraint, check constraint and not null constraint. If one of these constraints is violated, the database system will issue an error and terminate the statement without inserting any new row into the table.

It is not necessary to specify the columns if the sequence of values matches the order of the columns in the table. See the following INSERT statement that omits the column list in the INSERT INTO clause.

However, this is not considering as a good practice.

If you don’t specify a column and its value in the INSERT statement when you insert a new row, that column will take a default value specified in the table structure. The default value could be 0, a next integer value in a sequence, the current time, a NULL value, etc. See the following statement:

In this syntax, the column2 will take a default value.

Insert one row into a table example

We will use the employees and dependents tables in the sample database to show you how to insert one row into the table.

employees_dependents_tables

To insert a new row into the dependents table.

We did not use the department_id column in the INSERT statement because the dependent_id column is an auto-increment column, therefore, the database system uses the next integer number as the default value when you insert a new row.

The employee_id column is a foreign key that links the dependents table to the employees table. Before adding the new rows, the database system checks if the value 178 exists in the employee_id column of the employees table to make sure that the foreign key constraint is not violated.

If the row is inserted successfully, the database system returned the number of the affected rows.

You can check whether the row has been inserted successfully or not by using the following SELECT statement.

SQL INSERT one row example

Insert multiple rows into a table

To insert multiple rows using a single INSERT statement, you use the following construct:

For example, to insert two rows into the dependents table, you use the following query.

The database system returns 2 rows affected. You can verify the result using the following statement.

SQL INSERT multiple rows example

Copy rows from other tables

You can use the INSERT statement to query data from one or more tables and insert it into another table as follows:

In this syntax, you use a SELECT which is called a subselect instead of the VALUES clause . The subselect can contain the joins so that you can combine data from multiple tables. When executing the statement, the database system evaluates the subselect first before inserting data.

Suppose, you have a table named dependents_archive that has the same structure as the dependents table. The following statement copies all rows from the dependents table to the dependents_archive table.

You can verify the insert operation by using the following statement.

SQL INSERT copy rows from other tables example

Now you should know how to use the SQL INSERT statement to insert one or more rows into a table.

Артём Саннников

Данная книга является руководством для начинающих специалистов в области анализа и обработки данных. В книге рассматривается язык SQL и его процедурное расширение PL/SQL от компании Oracle.

Добавление данных в SQL, команда INSERT

Команда INSERT позволяет добавлять строки в таблицу базы данных, и это можно выполнить тремя способами:

  • добавить одну полную строку;
  • добавить часть одной строки;
  • добавить результаты запроса.
Добавление полных строк

Самый простой способ добавления данных в таблицу реализуется с помощью базового синтаксиса команды INSERT . Для этого нужно указать имя таблицы и значения, которые должны быть добавлены в новую строку.

Важный момент: столбцы должны заполняться в порядке, в котором они перечислены в определении таблицы.

Если использовать полный синтаксис команды INSERT , то он выглядит следующим образом:

Добавление части строки

Только что мы рассмотрели метод добавление данных в таблицу — добавления полных строк, и он заключается в том, чтобы указывать в явном виде имена столбцов таблицы. А если понадобится добавить только часть строки, то для этого нужно всего лишь пропустить не нужные столбцы в таблице.

Чтобы осуществить пропуск столбцов в таблице, должно соблюдаться одно из условий:

  • столбец определен как допускающий значения NULL (отсутствия какого-либо значения);
  • в определении столбца задано по умолчанию.
Добавление результатов запроса

Обычно команда INSERT служит для добавления строки в таблицу с использованием явно заданных значений. Существует и другая форма инструкции INSERT , которую можно применять для добавления результатов запроса SELECT . Такая инструкция называется INSERT SELECT и, как показывает её название, выполняет то же самое что и команды INSERT и SELECT по отдельности.

Как добавить новые строки в sql

INSERT inserts new rows into a table. One can insert one or more rows specified by value expressions, or zero or more rows resulting from a query.

The target column names can be listed in any order. If no list of column names is given at all, the default is all the columns of the table in their declared order; or the first N column names, if there are only N columns supplied by the VALUES clause or query . The values supplied by the VALUES clause or query are associated with the explicit or implicit column list left-to-right.

Each column not present in the explicit or implicit column list will be filled with a default value, either its declared default value or null if there is none.

If the expression for any column is not of the correct data type, automatic type conversion will be attempted.

INSERT into tables that lack unique indexes will not be blocked by concurrent activity. Tables with unique indexes might block if concurrent sessions perform actions that lock or modify rows matching the unique index values being inserted; the details are covered in Section 64.5. ON CONFLICT can be used to specify an alternative action to raising a unique constraint or exclusion constraint violation error. (See ON CONFLICT Clause below.)

The optional RETURNING clause causes INSERT to compute and return value(s) based on each row actually inserted (or updated, if an ON CONFLICT DO UPDATE clause was used). This is primarily useful for obtaining values that were supplied by defaults, such as a serial sequence number. However, any expression using the table’s columns is allowed. The syntax of the RETURNING list is identical to that of the output list of SELECT . Only rows that were successfully inserted or updated will be returned. For example, if a row was locked but not updated because an ON CONFLICT DO UPDATE . WHERE clause condition was not satisfied, the row will not be returned.

You must have INSERT privilege on a table in order to insert into it. If ON CONFLICT DO UPDATE is present, UPDATE privilege on the table is also required.

If a column list is specified, you only need INSERT privilege on the listed columns. Similarly, when ON CONFLICT DO UPDATE is specified, you only need UPDATE privilege on the column(s) that are listed to be updated. However, ON CONFLICT DO UPDATE also requires SELECT privilege on any column whose values are read in the ON CONFLICT DO UPDATE expressions or condition .

Use of the RETURNING clause requires SELECT privilege on all columns mentioned in RETURNING . If you use the query clause to insert rows from a query, you of course need to have SELECT privilege on any table or column used in the query.

Parameters

Inserting

This section covers parameters that may be used when only inserting new rows. Parameters exclusively used with the ON CONFLICT clause are described separately.

The WITH clause allows you to specify one or more subqueries that can be referenced by name in the INSERT query. See Section 7.8 and SELECT for details.

It is possible for the query ( SELECT statement) to also contain a WITH clause. In such a case both sets of with_query can be referenced within the query , but the second one takes precedence since it is more closely nested.

The name (optionally schema-qualified) of an existing table.

A substitute name for table_name . When an alias is provided, it completely hides the actual name of the table. This is particularly useful when ON CONFLICT DO UPDATE targets a table named excluded , since that will otherwise be taken as the name of the special table representing the row proposed for insertion.

The name of a column in the table named by table_name . The column name can be qualified with a subfield name or array subscript, if needed. (Inserting into only some fields of a composite column leaves the other fields null.) When referencing a column with ON CONFLICT DO UPDATE , do not include the table’s name in the specification of a target column. For example, INSERT INTO table_name . ON CONFLICT DO UPDATE SET table_name.col = 1 is invalid (this follows the general behavior for UPDATE ).

OVERRIDING SYSTEM VALUE

If this clause is specified, then any values supplied for identity columns will override the default sequence-generated values.

For an identity column defined as GENERATED ALWAYS , it is an error to insert an explicit value (other than DEFAULT ) without specifying either OVERRIDING SYSTEM VALUE or OVERRIDING USER VALUE . (For an identity column defined as GENERATED BY DEFAULT , OVERRIDING SYSTEM VALUE is the normal behavior and specifying it does nothing, but PostgreSQL allows it as an extension.)

OVERRIDING USER VALUE

If this clause is specified, then any values supplied for identity columns are ignored and the default sequence-generated values are applied.

This clause is useful for example when copying values between tables. Writing INSERT INTO tbl2 OVERRIDING USER VALUE SELECT * FROM tbl1 will copy from tbl1 all columns that are not identity columns in tbl2 while values for the identity columns in tbl2 will be generated by the sequences associated with tbl2 .

All columns will be filled with their default values, as if DEFAULT were explicitly specified for each column. (An OVERRIDING clause is not permitted in this form.)

An expression or value to assign to the corresponding column.

The corresponding column will be filled with its default value. An identity column will be filled with a new value generated by the associated sequence. For a generated column, specifying this is permitted but merely specifies the normal behavior of computing the column from its generation expression.

A query ( SELECT statement) that supplies the rows to be inserted. Refer to the SELECT statement for a description of the syntax.

An expression to be computed and returned by the INSERT command after each row is inserted or updated. The expression can use any column names of the table named by table_name . Write * to return all columns of the inserted or updated row(s).

A name to use for a returned column.

ON CONFLICT Clause

The optional ON CONFLICT clause specifies an alternative action to raising a unique violation or exclusion constraint violation error. For each individual row proposed for insertion, either the insertion proceeds, or, if an arbiter constraint or index specified by conflict_target is violated, the alternative conflict_action is taken. ON CONFLICT DO NOTHING simply avoids inserting a row as its alternative action. ON CONFLICT DO UPDATE updates the existing row that conflicts with the row proposed for insertion as its alternative action.

conflict_target can perform unique index inference . When performing inference, it consists of one or more index_column_name columns and/or index_expression expressions, and an optional index_predicate . All table_name unique indexes that, without regard to order, contain exactly the conflict_target -specified columns/expressions are inferred (chosen) as arbiter indexes. If an index_predicate is specified, it must, as a further requirement for inference, satisfy arbiter indexes. Note that this means a non-partial unique index (a unique index without a predicate) will be inferred (and thus used by ON CONFLICT ) if such an index satisfying every other criteria is available. If an attempt at inference is unsuccessful, an error is raised.

ON CONFLICT DO UPDATE guarantees an atomic INSERT or UPDATE outcome; provided there is no independent error, one of those two outcomes is guaranteed, even under high concurrency. This is also known as UPSERT — “ UPDATE or INSERT ” .

Specifies which conflicts ON CONFLICT takes the alternative action on by choosing arbiter indexes. Either performs unique index inference , or names a constraint explicitly. For ON CONFLICT DO NOTHING , it is optional to specify a conflict_target ; when omitted, conflicts with all usable constraints (and unique indexes) are handled. For ON CONFLICT DO UPDATE , a conflict_target must be provided.

conflict_action specifies an alternative ON CONFLICT action. It can be either DO NOTHING , or a DO UPDATE clause specifying the exact details of the UPDATE action to be performed in case of a conflict. The SET and WHERE clauses in ON CONFLICT DO UPDATE have access to the existing row using the table’s name (or an alias), and to the row proposed for insertion using the special excluded table. SELECT privilege is required on any column in the target table where corresponding excluded columns are read.

Note that the effects of all per-row BEFORE INSERT triggers are reflected in excluded values, since those effects may have contributed to the row being excluded from insertion.

The name of a table_name column. Used to infer arbiter indexes. Follows CREATE INDEX format. SELECT privilege on index_column_name is required.

Similar to index_column_name , but used to infer expressions on table_name columns appearing within index definitions (not simple columns). Follows CREATE INDEX format. SELECT privilege on any column appearing within index_expression is required.

When specified, mandates that corresponding index_column_name or index_expression use a particular collation in order to be matched during inference. Typically this is omitted, as collations usually do not affect whether or not a constraint violation occurs. Follows CREATE INDEX format.

When specified, mandates that corresponding index_column_name or index_expression use particular operator class in order to be matched during inference. Typically this is omitted, as the equality semantics are often equivalent across a type’s operator classes anyway, or because it’s sufficient to trust that the defined unique indexes have the pertinent definition of equality. Follows CREATE INDEX format.

Used to allow inference of partial unique indexes. Any indexes that satisfy the predicate (which need not actually be partial indexes) can be inferred. Follows CREATE INDEX format. SELECT privilege on any column appearing within index_predicate is required.

Explicitly specifies an arbiter constraint by name, rather than inferring a constraint or index.

An expression that returns a value of type boolean . Only rows for which this expression returns true will be updated, although all rows will be locked when the ON CONFLICT DO UPDATE action is taken. Note that condition is evaluated last, after a conflict has been identified as a candidate to update.

Note that exclusion constraints are not supported as arbiters with ON CONFLICT DO UPDATE . In all cases, only NOT DEFERRABLE constraints and unique indexes are supported as arbiters.

INSERT with an ON CONFLICT DO UPDATE clause is a “ deterministic ” statement. This means that the command will not be allowed to affect any single existing row more than once; a cardinality violation error will be raised when this situation arises. Rows proposed for insertion should not duplicate each other in terms of attributes constrained by an arbiter index or constraint.

Note that it is currently not supported for the ON CONFLICT DO UPDATE clause of an INSERT applied to a partitioned table to update the partition key of a conflicting row such that it requires the row be moved to a new partition.

It is often preferable to use unique index inference rather than naming a constraint directly using ON CONFLICT ON CONSTRAINT constraint_name . Inference will continue to work correctly when the underlying index is replaced by another more or less equivalent index in an overlapping way, for example when using CREATE UNIQUE INDEX . CONCURRENTLY before dropping the index being replaced.

Outputs

On successful completion, an INSERT command returns a command tag of the form

If the INSERT command contains a RETURNING clause, the result will be similar to that of a SELECT statement containing the columns and values defined in the RETURNING list, computed over the row(s) inserted or updated by the command.

Notes

If the specified table is a partitioned table, each row is routed to the appropriate partition and inserted into it. If the specified table is a partition, an error will occur if one of the input rows violates the partition constraint.

You may also wish to consider using MERGE , since that allows mixing INSERT , UPDATE , and DELETE within a single statement. See MERGE .

Examples

Insert a single row into table films :

In this example, the len column is omitted and therefore it will have the default value:

This example uses the DEFAULT clause for the date columns rather than specifying a value:

To insert a row consisting entirely of default values:

To insert multiple rows using the multirow VALUES syntax:

This example inserts some rows into table films from a table tmp_films with the same column layout as films :

This example inserts into array columns:

Insert a single row into table distributors , returning the sequence number generated by the DEFAULT clause:

Increment the sales count of the salesperson who manages the account for Acme Corporation, and record the whole updated row along with current time in a log table:

Insert or update new distributors as appropriate. Assumes a unique index has been defined that constrains values appearing in the did column. Note that the special excluded table is used to reference values originally proposed for insertion:

Insert a distributor, or do nothing for rows proposed for insertion when an existing, excluded row (a row with a matching constrained column or columns after before row insert triggers fire) exists. Example assumes a unique index has been defined that constrains values appearing in the did column:

Insert or update new distributors as appropriate. Example assumes a unique index has been defined that constrains values appearing in the did column. WHERE clause is used to limit the rows actually updated (any existing row not updated will still be locked, though):

Insert new distributor if possible; otherwise DO NOTHING . Example assumes a unique index has been defined that constrains values appearing in the did column on a subset of rows where the is_active Boolean column evaluates to true :

Compatibility

INSERT conforms to the SQL standard, except that the RETURNING clause is a PostgreSQL extension, as is the ability to use WITH with INSERT , and the ability to specify an alternative action with ON CONFLICT . Also, the case in which a column name list is omitted, but not all the columns are filled from the VALUES clause or query , is disallowed by the standard. If you prefer a more SQL standard conforming statement than ON CONFLICT , see MERGE .

The SQL standard specifies that OVERRIDING SYSTEM VALUE can only be specified if an identity column that is generated always exists. PostgreSQL allows the clause in any case and ignores it if it is not applicable.

Possible limitations of the query clause are documented under SELECT .

Prev Up Next
IMPORT FOREIGN SCHEMA Home LISTEN

Submit correction

If you see anything in the documentation that is not correct, does not match your experience with the particular feature or requires further clarification, please use this form to report a documentation issue.

Похожие публикации:

  1. Collation sql server что это
  2. Identity specification sql что это
  3. Microsoft sql server 2012 native client что это
  4. Ms sql named pipes что это

Как вставить в существующую таблицу новые строки? (Это в цикле с процедурами)

(Tablename2 — по задумке, в неё должны сохраниться результаты всех остальных вызовов процедуры на следующих шагах цикла. В результате должна поучиться огромная таблица с результатами выгрузки со всех шагов)

  1. На следующих шагах цикла я хочу вставить в эту же таблицу новые данные — результат вызова процедуры (которая перезаписала таблицу Tablename1). insert into schemaname.Tablename2 select * from schemaname.Tablename1

Но ничего не получается. Ошибка: Tablename2 уже существует в вашей базе.

P.s.: разные способы с insert value с перечислением имен полей, куда надо вставить данные, здесь бессильны, т.к. полей больше 200.

Буду благодарна за любые идеи — как исправить эту ошибку.

Спасибо за внимание!

declare @num_int int IF OBJECT_ID('Analysis.dbo.TA_FinUsers_AllPeriod') IS NOT NULL DROP TABLE Analysis.dbo.TA_FinUsers_AllPeriod; /* determine object of cursor for the loop: it is a "serial number" for each "panel" from the table TA_Dates*/ declare db_cursor cursor for select num_ from dbo.TA_Dates /* go to loop */ open db_cursor /* declare variable, wich will run from step to step in the loop and catch the current value of cursor */ fetch next from db_cursor into @num_int while @@FETCH_STATUS = 0 begin print @num_int declare @endd_ datetime declare @ndays_ int declare @Year__ int declare @Month__ int /* set value for our first variables (next - use it in the fetching procedure)*/ select @endd_ = End_Datetime from dbo.TA_Dates where num_ = @num_int; print @endd_ select @ndays_ = Days_in_Period from dbo.TA_Dates where num_ = @num_int; print @ndays_ select @Year__ = Year_ from dbo.TA_Dates where num_ = @num_int; print @Year__ select @Month__ = Month_ from dbo.TA_Dates where num_ = @num_int; print @Month__ EXEC Fetch_Execute @endd = @endd_, @ndays = @ndays_, @reg = 0, @par = 0, @par_end = 22, @Year_ = @Year__ , @Month_ = @Month__ ; if (@num_int = 1) begin select * into Analysis.dbo.TA_FinUsers_AllPeriod from Analysis.dbo.TA_FinUsers end; if (@num_int > 1) begin insert into Analysis.dbo.TA_FinUsers_AllPeriod select * from Analysis.dbo.TA_FinUsers end; fetch next from db_cursor into @num_int print @num_int end close db_cursor deallocate db_cursor 

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *