Pl sql merge: Oracle PL/SQL оператор MERGE — Oracle PL/SQL •MySQL •MariaDB •SQL Server •SQLite

SQL exercises




SQL exercises

Language  Русский English

April 05, 05:39 MSK








Ratings

Statistics

SQL exercises

Forums

Certification

HELP

Query optimization

Personal page
Developers & Thanks
For employers
References
Feedback
Support SQL-EX. RU





Документы




Today we have 70 visitors (5 new).
4 exercises solved (1 on SELECT and 3 on DML),

on learning stage — 108

Site news 2022-12-23
All the news    Week news
Certified within this week:

Last certified.

Confirm certificate



Happy Birthday to:


Buldenkov D. A. (eXeQuThor)

!!!


The nearest birthdays.





Telegram channel SQL-Ex.


Top 100 on latest exercises.


Visual modelling (Painting database).




There are exercises on SELECT statement (presently 182 exercises on learn stage and 238 exercises on rating stages) and on other
data manipulation operators — INSERT, UPDATE, DELETE, and MERGE (55 exercises).
The rating of members is carried on SELECT exercises. See test conditions.




The book «SQL. Problems and solutions» , which is analyzing the characteristic mistakes admitted at the solution of the learn-stage exercises on the site, was originally published in Peter Publishing Company.


Read last site news.


Practical skills of SQL language

This site will help everyone to gain or improve skills in building
SQL Data Manipulation Language statements. To train You will have to build yourself
the SQL statements for retrieval or modification of specific data required in the exercises.
When Your query is incorrect, You will be able to see rows returned by the correct
query along with that returned by Your query. Furthermore, you may execute arbitrary
DML statements on available databases by setting the «Without checking» option. There are
five levels of difficulty (from 1 to 5), You may see it in second column of
exercises list. We propose the exercises on retrieving data (SELECT statement) and
the exercises on modifying data (INSERT, UPDATE, DELETE, and MERGE statements). Your success in the solving the exercises are shown by a rating of participants.
As this takes place, there are three stages:
the first one (first 5 exercises) is performed without time control for an individual
exercise, the second one (begins with the exercise #6) controls time for completion of each
task. At the third stage which refers to optimizing and begins with exercise #139, it is required not only to solve an exercise correctly, but also time of execution of inquiry should be commensurable with time of execution of the author’s solution.

Exercises of the first stage are available without registration and may be solved
in any order You like. The solution of the rest of exercises requires registration.
REGISTRATION IS FREE as this for all other services of the site. In the third column of exercises list You
will be able to see («OK») notes with the numbers of done exercises, but that
is available only to the registered users. In fact, that is the main reason for registration.
If You would like to visit our web site again, You won’t have to recollect which
exercises You have done already and which You haven’t. If You don’t want to register,
You may enter as a guest, but in that case Your results won’t
be traced by the system. Registered users also may discuss the solutions to exercises in our forum.


NOTE: The query stated incorrectly may return the «correct» data on a current state of database.
For this reason You should not be surprised if the results of incorrect query are
coincide with the results of right one with Your query is estimated as incorrect by the Verifying system.

NOTE: Your browser should support Cookies and Javascript to provide correct usage of this site. If you use content filter, it should allow opening child windows to explore help pages.

Certification

Successful testing of yours can be confirmed by the certificate «SQL Data Manipulation Language Specialist».
We support quality of our certificate by periodically replacing exercises and changing
the certificate requirements.

More about certification. What does the certificate give to you?


SQL syntax used

User’s queries are executed by SQL server that brings some limitations to the
syntax of SQL statements. Now we use Microsoft SQL Server 2019 (15.0) on the rating stages,
and MariaDB-10.4 (compatible with MySQL 8), PostgreSQL 12.3, and Oracle Database 11g on the learn stage in addition. That is why You should follow
the syntax of these realizations when building queries. It should be noted that SQL syntax,
implemented in Microsoft SQL Server, is close to that of SQL-92 standard. But there are some
distinctions, among them is absence of NATURAL JOIN of tables. Supplied help on SQL Data Manipulation Language is held in accordance
with SQL-92 standard and contains information necessary for solving the exercises. In the same place it is possible to find features of used realization (SQL Server 2005).

Top 10 results


PersonScoresDaysDays_2Days_3Scores_3
Chernov D.V. (Kursist)70620811602.3881710.888256
Filippkin D.V. (_dimon_)7075040224.192156.502255
Doschenko V.N. (mcrain)67138782042. 874525.210252
Kostomarov A.V. (al29)64932794333.7822473.867251
Kreslavskij O.M. (Arcan)6955467284.368225.498248
Krasovskij E.A. (pegoopik)6734519210.57714.367248
Bezhaev A.Yu. (Baser)6614678266.002347.687240
Boiko D. (Angellore)65451385433.7553825.743237
Dubinskij A.V. (_velial)65241202797.4683371.376227
Karasyova N.V. (vlksm)6675809291.756242.855225



plsql — Как использовать ключевое слово MERGE в pl/sql?

спросил

Изменено
1 год, 1 месяц назад

Просмотрено
118 раз

Я обновляю таблицу, но продолжаю получать следующую ошибку

 ОШИБКА: синтаксическая ошибка в или около «СЛИЯНИЯ»
СТРОКА 3: ОБЪЕДИНИТЬСЯ в
 

, когда я пытаюсь использовать оператор слияния. Я не вижу ничего очевидного в синтаксисе. может кто-нибудь указать на очевидное

 MERGE в Table2 t2
используя (выберите имя, max (id) max_id из группы Table1 t1 по имени) t1
на (t2.project_name=t1.name)
при совпадении обновите set projectid=max_id, где status='congoing' ;
 

Таблица 1

 1 | альфа | 2021 |
2 | фундамент | 2020 |
3 | НЕТОС | 2021 |
5 | ВебОПД | 2019 |
Таблица 2
идентификатор | имя | год | статус | название проекта | идентификатор проекта
1 | Джон | 2021 | текущий | альфа | 1
2 | Линда | 2021 | завершено | НЕТОС | 3
3 | погладить | 2021 | ВебОПД | завершено | 5
4 | том | 2021 | текущий | альфа | 1
 

версия: PostgreSQL 13.6

1

В последней строке вашего сообщения говорится, что вы используете PostgreSQL . Используемый вами тег ( plsql ) означает Oracle . Какой же он, в конце концов? Я предполагаю, что раньше, но синтаксис, который вы использовали, — это Oracle.

Документация MERGE для PostgreSQL говорит, что

  • INTO нельзя использовать
  • без скобок для ПО пункт
  • Условие WHERE нельзя использовать

Посмотрите, поможет ли это:

 MERGE Table2 t2
используя (выберите t1.name,
              макс(t1.id) max_id
       из таблицы 1 t1 присоединиться к таблице 2 t2 на t2.project_name = t1.name
       где t2.status = 'текущий'
       группировать по имени
      ) Икс
на t2.project_name = x.name
при совпадении обновите набор
  t2.projectid = x.max_id ;
 

1

Зарегистрируйтесь или войдите в систему

Зарегистрируйтесь с помощью Google

Зарегистрироваться через Facebook

Зарегистрируйтесь, используя электронную почту и пароль

Опубликовать как гость

Электронная почта

Обязательно, но не отображается

Опубликовать как гость

Электронная почта

Требуется, но не отображается

Как при выполнении MERGE в Oracle SQL обновить строки, которые не совпадают в SOURCE

У меня есть основная база данных и база данных отчетов, и мне нужно синхронизировать таблицу из основной в отчет.

Однако, когда элемент удаляется из основной базы данных, я хочу установить только флаг IsDeleted в базе данных отчетов.

Какой элегантный способ сделать это?

В настоящее время я использую оператор MERGE, например:

 MERGE INTO report.TEST target
ИСПОЛЬЗОВАНИЕ (SELECT * FROM main.TEST) источника
   ВКЛ (целевой.ID = исходный.ID)
КОГДА СООТВЕТСТВУЕТ ТО
    НАБОР ОБНОВЛЕНИЯ (цель... = источник...)
КОГДА НЕ СООТВЕТСТВУЕТ ТО
    ВСТАВИТЬ (...) ЗНАЧЕНИЯ (источник...)
;
 

Оператор WHEN NOT MATCHED дает мне все НОВЫЕ значения из основного, но я также хочу обновить все СТАРЫЕ значения из отчета.

Я использую Oracle PL/SQL.


 

  • sql
  • оракул
  • SQL-слияние

4 ноября 2022 г.

в других

к
гаурав

• 22,970 баллов

248 просмотров

1 ответ на этот вопрос.

0 голосов

Вижу, ты уже давно об этом спрашивал, надеюсь, это все же поможет.

У меня была такая же проблема, и вот как я ее решил. (отображается в вашем коде)

 @State private var минимум: Double = 98.0
Максимум частной переменной @State: Double = 1000000,0
var filteredProducts: [Продукт]
var body: некоторый View {
    Список {
        Раздел(заголовок: Текст("Фильтры")){
            DisclosureGroup("Ценовой диапазон") {
                Ползунок (значение: $минимум, в: 98...максимум) {
                    Текст("\(минимум)")
                } minValueLabel: {
                    Текст("мин")
                } maxValueLabel: {
                    Текст("\(максимум, спецификатор: "%.0f")")
                }
                
                Ползунок (значение: максимум $, в: минимум... 1000000) {
                    Текст("\(максимум)")
                } minValueLabel: {
                    Text("\(минимум, спецификатор: "%.0f")
                } maxValueLabel: {
                    Текст("\(максимум, спецификатор: "%.0f")")
                }
            }
        }
    }
}
 

По сути, задайте ползунку минимального значения максимальное значение @state и наоборот для ползунка максимального значения.

ответил

7 ноября 2022 г.

к
гаурав

• 22 970 баллов

Связанные вопросы в других

В SQL Server можно вставить … ПОДРОБНЕЕ

ответил

30 мая 2022 г.

в других

к
Аниша

• 140 баллов

139Просмотры

  • sql
  • sql-сервер
  • выберите
  • тскл

Сначала мы можем использовать оператор SELECT для получения … ПОДРОБНЕЕ

ответил

27 мая 2022 г.

в других

к
Авинаш

• 240 баллов

265 просмотров

  • sql
  • sql-сервер
  • тскл
  • выберите
  • SQL-обновление

Попробуй это:
Частное сканирование как целое число
Private Sub CommandButton1_Click() … ПОДРОБНЕЕ

ответил

24 октября 2022 г.

в других

к
нариккадан

• 61,900 баллов

241 просмотр

  • первенствовать
  • вба

Делать то, что вы хотите, это как . .. ПОДРОБНЕЕ

ответил

24 ноября 2022 г.

в других

к
нариккадан

• 61,900 баллов

258 просмотров

  • первенствовать
  • голубая призма
  • рпа

В зависимости от деталей вашего сценария … ПОДРОБНЕЕ

ответил

17 июля 2018 г.

в Другие вопросы DevOps

к
айс3033

• 7 300 баллов

433 просмотра

  • Девопс
  • нолио
  • sql
  • оракул
  • devops-инструменты

Неа. Я не думаю, что есть один
Но… ПОДРОБНЕЕ

ответил

10 октября 2018 г.

в базе данных

к
Неха

• 6 300 баллов

488 просмотров

  • оракул
  • sql
  • база данных

Для выполнения запросов Oracle SQL и PL/SQL … ПОДРОБНЕЕ

ответил

11 февраля 2022 г.

в базе данных

к
Неха

• 8 940 баллов

525 просмотров

  • sql
  • PLSQL
  • оракул
  • саас

Преобразование CSV в SQL
http://www.