Ошибка СУБД: Обработчик запросов исчерпал внутренние ресурсы… |
Я |
18.01.12 — 06:16
Периодически, не всегда, выдает на формирование ОСВ за год вот такую ошибку:
Ошибка СУБД:
Microsoft OLE DB Provider for QSL Server: Обработчик запросов исчерпал внутренние ресурсы, и ему не удалось предоставить план запроса.
Это редкое событие, которое может происходить только при очень сложных запросах или запросах, которые обращаются к очень большому числу таблиц или секций.
Упростите запрос…
Сервер на базе i5, ОЗУ=8Гб. 64-битный 1С Сервер. SQL 2008.
Как можно лечить? Поможет ли увеличение оперативки?
1 — 18.01.12 — 06:21
(0) Упрости запрос.
2 — 18.01.12 — 06:27
(1) бухам нужен ОСВ за год по всем счетам, упрощать не собираются, к тому же он иногда отрабатывает. след. можно как-то лечить
3 — 18.01.12 — 06:29
(2) Можно разбить запрос на несколько, использовать временные таблицы и т.д.
4 — 18.01.12 — 06:30
(3) все не то, не полезу я им новый ОСВ писать, мне кажется дело в настройках СКЛ, только что там настроть можно — ума не приложу
5 — 18.01.12 — 06:35
(4) Попробуй посмотреть, что говорит sp_configure.
6 — 18.01.12 — 06:36
(5) а что это? я не силен в скл
7 — 18.01.12 — 06:39
8 — 18.01.12 — 06:40
(7) ок, посмтрю
9 — 18.01.12 — 06:41
+(7) Только, IMHO, всё же лучше попробовать упростить запрос. Не переписывая всё, только попробовать слегка оптимизировать. Например, IN (SELECT если есть — заменить на что-нибудь полегче. И вообще подзапросы повыносить во временные таблицы.
10 — 18.01.12 — 06:47
(9) но иногда же отрабатывает, это наводит на мысль…
11 — 18.01.12 — 06:51
(10) Оно, конечно, так…
Но если жрёт ресурсы безбожно — то где гарантия, что подкинешь ты ему ресурсов, а оно их снова не сожрёт? Тем более что дальше база будет расти и расти…
Я не настаиваю, посмотри настройки sp_configure — там могут стоять ограничения. Но, IMHO, соптимизировать запрос — обычно полезнее бывает.
12 — 18.01.12 — 07:35
(0) а покажите результат «SELECT @@version»
13 — 18.01.12 — 08:04
(12) как его показать, я скл не знаю, поставил и работает
14 — 18.01.12 — 08:10
релиз?
15 — 18.01.12 — 08:13
(13) Подключиться к SQL Server с помощью SQL Server Management Studio, нажать кнопку «New query», ввести SELECT @@version и нажать F5 (либо кнопку Execute)
16 — 18.01.12 — 08:17
Microsoft SQL Server 2008 R2 (RTM) — 10.50.1600.1 (X64) Apr 2 2010 15:48:46 Copyright (c) Microsoft Corporation Standard Edition (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1)
17 — 18.01.12 — 08:43
(16) Попробуйте, как вариант, поставить сервиспак — http://support.microsoft.com/kb/2528583
18 — 18.01.12 — 08:52
(17) ок, попробую
19 — 18.01.12 — 09:12
(2) Главному или всем? Если всем посылай их подальше. Пусть анализ счета и обороты смотрят по нему. Или список выдают…
20 — 18.01.12 — 09:14
Из тех счетов что смотреть…
Представляю себе ОСВ, ну очень крупного холдинга ))))
21 — 18.01.12 — 09:20
(20) главному; нет не холдинг, так себе конторка — это и бесит, какой то ОСВ за год
22 — 03.02.12 — 13:02
Может быть у пользователя установлены права с ограничением прав на уровне записи?
LanLion
23 — 24.02.12 — 16:14
Полный бред граждане это ошибка платформы 1с, скуля или релиза опять 1сники что-то улучшили, вылезла такая же гадость на днях да последних релизов такого небыло, работало все нормально и разворачивала и разворачивает намного более сложные отчеты. 1с позиционирует себя как ерп и т.д сажает себя на оракл и вытворяет такую ..ерню. Все тут советуют упростить запрос, а тем у кого конфа на поддержке да и вообще какого фига мы должны за них делать их работу это типовой отчет.
This is showing up in the logs several times a night. How do I find the query causing the issue? SQL Server 2008 R2 Sp1.
![]()
asked Nov 19, 2012 at 18:29
0
Look for queries with very long IN lists, a large number of UNIONs, or a large number of nested subqueries. These are the most common causes of this particular error message in my experience.
Occasionally the issue can be resolved by applying a product update (service pack or cumulative update) or enabling a supported trace flag, but more often the fundamental issue is the unusual SQL generated by some tools or data abstraction layers. The latter will require application changes, unfortunately.
Enabling documented trace flags 4102, 4118, 4122 (or the covering 4199) may also avoid the issue you are seeing. Review the documentation to see if they address the root cause in your case:
Microsoft Knowledge Base article for TF 4122
Microsoft Knowledge Base article for TF 4102, 4118
Microsoft Knowledge Base article for TF 4199
answered May 28, 2013 at 4:45
![]()
Paul White♦Paul White
76.5k27 gold badges386 silver badges604 bronze badges
I have solved a similar issue by using a server-side startup ‘tuning’ trace that runs in the background capturing statements running for over 1 second (you could perhaps set it to 10secs if you have an extremely busy server).
When the Query Processor fails to produce a plan it takes over 10 seconds to do so (in my experience)
The Errorlog entry does show the SPID involved along with the exact time, so going to the ‘tuning’ trace it is easy to identify the offending statement.
Surpisingly it may have a ‘success’ errorcode.
answered May 27, 2013 at 17:40
John AlanJohn Alan
1,0617 silver badges13 bronze badges
I received this error because of another reason which I didn’t see online, so I’m posting the problem and solution here.
This can happen when trying to modify an xml column by inserting a very large text.
For example…
update MyTable
set XmlColumn.modify('
insert
Very large text here...
after (/RootNode/Node)[1]')
where Id = 1
To fix it, you can use a sql variable to hold the large text
declare @MyXml xml
set @MyXml = 'Very large text here...'
update MyTable
set XmlColumn.modify('
insert
sql:variable("@MyXml")
after (/RootNode/Node)[1]')
where Id = 1
The method seems faster anyway so should probably be used whenever possible
answered Jun 24, 2015 at 18:55
Possible it is not one query causing the issue. If you are using a ton of ad-hoc queries it would be prudent to enable ‘optimize for ad-hoc workloads’. This way SQL Server will only create plans the second time a query is executed.
You can check using below SQL (Reference here):
SELECT objtype AS [CacheType]
, count_big(*) AS [Total Plans]
, sum(cast(size_in_bytes as decimal(18,2)))/1024/1024 AS [Total MBs]
, avg(usecounts) AS [Avg Use Count]
, sum(cast((CASE WHEN usecounts = 1 THEN size_in_bytes ELSE 0 END) as decimal(18,2)))/1024/1024 AS [Total MBs - USE Count 1]
, sum(CASE WHEN usecounts = 1 THEN 1 ELSE 0 END) AS [Total Plans - USE Count 1]
FROM sys.dm_exec_cached_plans
GROUP BY objtype
ORDER BY [Total MBs - USE Count 1] DESC
go
![]()
Kin Shah
61.6k5 gold badges115 silver badges235 bronze badges
answered Apr 25, 2013 at 21:11
0
This is showing up in the logs several times a night. How do I find the query causing the issue? SQL Server 2008 R2 Sp1.
![]()
asked Nov 19, 2012 at 18:29
0
Look for queries with very long IN lists, a large number of UNIONs, or a large number of nested subqueries. These are the most common causes of this particular error message in my experience.
Occasionally the issue can be resolved by applying a product update (service pack or cumulative update) or enabling a supported trace flag, but more often the fundamental issue is the unusual SQL generated by some tools or data abstraction layers. The latter will require application changes, unfortunately.
Enabling documented trace flags 4102, 4118, 4122 (or the covering 4199) may also avoid the issue you are seeing. Review the documentation to see if they address the root cause in your case:
Microsoft Knowledge Base article for TF 4122
Microsoft Knowledge Base article for TF 4102, 4118
Microsoft Knowledge Base article for TF 4199
answered May 28, 2013 at 4:45
![]()
Paul White♦Paul White
76.5k27 gold badges386 silver badges604 bronze badges
I have solved a similar issue by using a server-side startup ‘tuning’ trace that runs in the background capturing statements running for over 1 second (you could perhaps set it to 10secs if you have an extremely busy server).
When the Query Processor fails to produce a plan it takes over 10 seconds to do so (in my experience)
The Errorlog entry does show the SPID involved along with the exact time, so going to the ‘tuning’ trace it is easy to identify the offending statement.
Surpisingly it may have a ‘success’ errorcode.
answered May 27, 2013 at 17:40
John AlanJohn Alan
1,0617 silver badges13 bronze badges
I received this error because of another reason which I didn’t see online, so I’m posting the problem and solution here.
This can happen when trying to modify an xml column by inserting a very large text.
For example…
update MyTable
set XmlColumn.modify('
insert
Very large text here...
after (/RootNode/Node)[1]')
where Id = 1
To fix it, you can use a sql variable to hold the large text
declare @MyXml xml
set @MyXml = 'Very large text here...'
update MyTable
set XmlColumn.modify('
insert
sql:variable("@MyXml")
after (/RootNode/Node)[1]')
where Id = 1
The method seems faster anyway so should probably be used whenever possible
answered Jun 24, 2015 at 18:55
Possible it is not one query causing the issue. If you are using a ton of ad-hoc queries it would be prudent to enable ‘optimize for ad-hoc workloads’. This way SQL Server will only create plans the second time a query is executed.
You can check using below SQL (Reference here):
SELECT objtype AS [CacheType]
, count_big(*) AS [Total Plans]
, sum(cast(size_in_bytes as decimal(18,2)))/1024/1024 AS [Total MBs]
, avg(usecounts) AS [Avg Use Count]
, sum(cast((CASE WHEN usecounts = 1 THEN size_in_bytes ELSE 0 END) as decimal(18,2)))/1024/1024 AS [Total MBs - USE Count 1]
, sum(CASE WHEN usecounts = 1 THEN 1 ELSE 0 END) AS [Total Plans - USE Count 1]
FROM sys.dm_exec_cached_plans
GROUP BY objtype
ORDER BY [Total MBs - USE Count 1] DESC
go
![]()
Kin Shah
61.6k5 gold badges115 silver badges235 bronze badges
answered Apr 25, 2013 at 21:11
0
Оптимизация больших запросов
Вопрос:
Я пытаюсь запустить запрос, но он возвращает ошибку, которой недостаточно, чтобы ресурсы обрабатывали ее.
Запрос:
SELECT ID,
ISNULL(LINK,'0'),
FLOOR(ISNULL(AMOUNTPAID,'0')),
CONVERT(VARCHAR(8), DATEPAID, 5),
PAYSOURCE
FROM finance
WHERE DATEADD(month,24,DATEPAID) > GETDATE()
AND ID IN (A LIST OF IDs)
Первый выбор – около 1,4 миллиона результатов, а в списке ID – около 100 000 идентификаторов.
Есть ли другой способ построить этот запрос?
Ответ №1
Я предполагаю, что вы используете длинный список из 100 000 значений IN и видите эту ошибку
Обработчик запросов исчерпал внутренние ресурсы и не смог создать план запроса. Это редкое событие и ожидается только для чрезвычайно сложных запросов или запросов, которые ссылаются на очень большое количество таблиц или разделов. Пожалуйста, упростите запрос. Если вы считаете, что получили это сообщение по ошибке, обратитесь в Службу поддержки клиентов за дополнительной информацией.
По предложению в этом элементе Connect поместите список идентификаторов во временную таблицу или индексированный параметр таблицы.
Ответ №2
select ID,ISNULL(LINK,'0'),FLOOR(ISNULL(AMOUNTPAID,'0')),CONVERT(VARCHAR(8), DATEPAID, 5) ,PAYSOURCE
from dbo.finance f inner join listofid l on f.id=l.id
where DATEADD(month,24,DATEPAID) > GETDATE()
также вам нужно создать некластеризованный индекс для DATEPAID.hope id – pk. BTW, список id поступает из таблицы/переменной?
Я думаю, что запрос будет быстрым. Вы хотите сказать, что есть другой запрос, в который вы помещаете список id в переменную.
Bru_10
Дата регистрации: 08.04.2010
Сообщений: 65
Добрый день! Есть 2 базы ЗУП и Бух 2.0, выгружаю из зупа ведомости, кассовые документы и т.д(в общем стандартной выгрузкой) с детализацией по сотрудникам, в ведомости 230 человек, соответственно выгружается платежное поручение, при оплате приходит выписка, создается документ списание с расчетного счета. Открываем это списание выбираем вид операции расчеты по заработной плате, указываю эту ведоместь(где 230 человек) и пытаюсь провести и дальше выдается сообщение<br><br>hresult 80040e14 sqlstate 42000 native 8623<br>»обработчик запроса исчерпал внутренние ресурсы, и ему не удалось предоставить план запроса. и т.д»<br> <br>вариант работы клиент сервер, работаю под полными правами.<br> <br>если удаляю несколько строк, до 200, все проводится<br> <br>может кто подскажет как выйти из ситуации?
Мне нужно найти большое количество значений в моей базе данных.
Вот как могут выглядеть данные:
0054321
54321
999
999 - HALLO?
54321 Hallo?
000054321
Поскольку это одноразовая вещь, я подумал, что просто сделаю действительно длинный запрос, ищущий данные, используя OR и LIKE:
... WHERE ' ' + FLD1 + ' ' LIKE '%54321 %'
OR ' ' + FLD1 + ' ' LIKE '%999 %'
OR ...
Представьте себе это, но с 80k OR. В этом случае SQL Server столкнется со следующей проблемой:
Обработчик запросов исчерпал внутренние ресурсы и не смог создать план запроса. Это редкое событие, которое ожидается только для чрезвычайно сложных запросов или запросов, которые ссылаются на очень большое количество таблиц или разделов. Пожалуйста, упростите запрос. Если вы считаете, что получили это сообщение по ошибке, обратитесь в службу поддержки клиентов за дополнительной информацией.
В качестве обходного пути я прочитал, что вы должны объявить временную ТАБЛИЦУ и поместить туда свои значения, а затем выполнить поиск с помощью ‘IN’, но мне нужно искать с LIKE, чтобы я мог использовать подстановочные знаки.
Есть ли у кого-нибудь идеи, как решить или обойти эту проблему?
Я не хочу разделять команду на несколько команд одним и тем же методом.
Спасибо за ваши предложения!
1 ответ
Лучший ответ
Вы все еще можете использовать временную таблицу.
where exists (select 1
from patterntable pt
where ' ' + x.field1 + ' ' like pt.pattern
)
x — это псевдоним любой таблицы, из которой происходит поле.
Или же:
where ' ' + x.field1 + ' ' like '% ' + pt.pattern + ' %'
В зависимости от того, хотите ли вы хранить подстановочные знаки или нет.
1
Gordon Linoff
2 Июл 2019 в 21:22
Поэтому я пишу проект базы данных Visual Studio SQL для существующей базы данных.
Я создаю простые сценарии слияния в таблице для постоянных данных, существующих данных и т.д. И т.д. Это было относительно прямо вперед, пока я не пришел к одной конкретной таблице, которая дает мне ошибку в названии.
Теперь, если бы это был сложный запрос, я бы понял, но это не так, у него есть одно ключевое поле с кластерным индексом и без сложных операций. Я попытался удалить все проверки ISNULL из проверки MATCHED после первого И, и это все равно дает мне ту же ошибку. Я не понимаю!
Они являются [my_table_code], первым столбцом. Здесь основная часть запроса содержит только первую строку для ясности.
MERGE INTO [my_table] AS Target
USING (VALUES
(N'00001L',N'20160425',N'20160425',N'132011',N'DMTEAM',N'C',N'Name',N'F',365,0,N'19790702',N'20130418',N'20130418',N'20130418',N'20130418',N'',0.0,0.0,0,N'GBP',1.0,N'19790702',N'N',N'N',0,0,0,0,N'Y',N'SLAC Life Series 1',N'19790703',365,N'UK',-1,N'N',N'H',N'N',0,N'',N'ALL',N'10000101',N'',0,0,N'0',N'N',N'N',0.000000000000000e+000,N'',N'E',365,0,0,N'N',365,0,0,N'N',0,0,N'',N'',0,N'',N'DEF',N'',N'',0,0,N'',N'',-1,N' ',N' ',N' ',N' ',N' ',N'E',N' ',N'',N' ',N' ',N' ',0,1.5,4.5,7.5,0.0,0,N'0',N'0')
-- 2600 rows more
) AS Source ([my_table_code],[my_table_create_date],[my_table_last_updt_date],[my_table_last_updt_time],[my_table_last_updt_userid],[my_table_record_status],[my_table_name],[my_table_next_or_last_price],[my_table_pricing_frequency],[my_table_sell_pricing_frequency],[my_table_commenced_date],[my_table_closed_date],[my_table_closed_for_newbus_date],[my_table_closed_for_spi_date],[my_table_closed_for_money_date],[my_table_category],[my_table_spread_relationship],[my_table_management_charge],[my_table_sellout_period_mths],[my_table_currency],[my_table_price_tolerance],[my_table_initial_price_date],[my_table_last_date_in_period],[my_table_sell_last_date_in_period],[my_table_last_day_in_period],[my_table_sell_last_day_in_period],[my_table_same_day_in_period],[my_table_sell_same_day_in_period],[my_table_use_working_days],[my_table_external_id],[my_table_post_initial_price_date],[my_table_price_applies_frequency],[my_table_price_country_code],[my_table_non_working_price_days_adj],[my_table_pricing_calendar],[my_table_risk_profile],[my_table_pay_dividend],[my_table_dividend_frequency],[my_table_sedol],[my_table_type],[my_table_strike_date],[my_table_maturity_date],[my_table_amc_basis_no],[my_table_coupon_select_id],[my_table_coupon_defaults],[my_table_whole_units],[my_table_clone_by_policy],[my_table_initial_clone_price],[my_table_price_base_calc_date],[my_table_group],[my_table_disinv_notice_freq],[my_table_disinv_notice_value],[my_table_disinv_same_day_in_period],[my_table_disinv_notice_last_date],[my_table_trade_cutoff_freq],[my_table_trade_cutoff_value],[my_table_trade_cutoff_same_day_in_period],[my_table_trade_cutoff_last_date],[my_table_expected_delay_rules],[my_table_settlement_days],[my_table_bid_offer_exception_rules],[my_table_holding_fund_id],[my_table_timeout_days],[my_table_price_valuation_basis],[my_table_classification],[my_table_target_days],[my_table_sell_target_days],[my_table_disinv_same_day_period_skip],[my_table_trade_cutoff_same_day_period_skip],[my_table_equity_sector],[my_table_client_classification],[my_table_max_decimal_places],[my_table_rounding_method],[my_table_closing_time],[my_table_rounding_direction],[my_table_use_external_WS],[my_table_gl_code],[my_table_asset_class],[my_table_grouping],[my_table_factsheet_url],[my_table_aladdin_ticker],[my_table_manager],[my_table_use_notice_for_backdates],[my_table_business_date_delay],[my_table_growth_low],[my_table_growth_med],[my_table_growth_high],[my_table_growth_SMPI],[my_table_instruction_file_decimal_places],[my_table_suspend_start_date],[my_table_suspend_end_date])
ON (Target.[my_table_code] = Source.[my_table_code])
WHEN MATCHED AND (
NULLIF(Source.[my_table_create_date], Target.[my_table_create_date]) IS NOT NULL OR NULLIF(Target.[my_table_create_date], Source.[my_table_create_date]) IS NOT NULL OR
NULLIF(Source.[my_table_last_updt_date], Target.[my_table_last_updt_date]) IS NOT NULL OR NULLIF(Target.[my_table_last_updt_date], Source.[my_table_last_updt_date]) IS NOT NULL OR
NULLIF(Source.[my_table_last_updt_time], Target.[my_table_last_updt_time]) IS NOT NULL OR NULLIF(Target.[my_table_last_updt_time], Source.[my_table_last_updt_time]) IS NOT NULL OR
NULLIF(Source.[my_table_last_updt_userid], Target.[my_table_last_updt_userid]) IS NOT NULL OR NULLIF(Target.[my_table_last_updt_userid], Source.[my_table_last_updt_userid]) IS NOT NULL OR
NULLIF(Source.[my_table_record_status], Target.[my_table_record_status]) IS NOT NULL OR NULLIF(Target.[my_table_record_status], Source.[my_table_record_status]) IS NOT NULL OR
NULLIF(Source.[my_table_name], Target.[my_table_name]) IS NOT NULL OR NULLIF(Target.[my_table_name], Source.[my_table_name]) IS NOT NULL OR
NULLIF(Source.[my_table_next_or_last_price], Target.[my_table_next_or_last_price]) IS NOT NULL OR NULLIF(Target.[my_table_next_or_last_price], Source.[my_table_next_or_last_price]) IS NOT NULL OR
NULLIF(Source.[my_table_pricing_frequency], Target.[my_table_pricing_frequency]) IS NOT NULL OR NULLIF(Target.[my_table_pricing_frequency], Source.[my_table_pricing_frequency]) IS NOT NULL OR
NULLIF(Source.[my_table_sell_pricing_frequency], Target.[my_table_sell_pricing_frequency]) IS NOT NULL OR NULLIF(Target.[my_table_sell_pricing_frequency], Source.[my_table_sell_pricing_frequency]) IS NOT NULL OR
NULLIF(Source.[my_table_commenced_date], Target.[my_table_commenced_date]) IS NOT NULL OR NULLIF(Target.[my_table_commenced_date], Source.[my_table_commenced_date]) IS NOT NULL OR
NULLIF(Source.[my_table_closed_date], Target.[my_table_closed_date]) IS NOT NULL OR NULLIF(Target.[my_table_closed_date], Source.[my_table_closed_date]) IS NOT NULL OR
NULLIF(Source.[my_table_closed_for_newbus_date], Target.[my_table_closed_for_newbus_date]) IS NOT NULL OR NULLIF(Target.[my_table_closed_for_newbus_date], Source.[my_table_closed_for_newbus_date]) IS NOT NULL OR
NULLIF(Source.[my_table_closed_for_spi_date], Target.[my_table_closed_for_spi_date]) IS NOT NULL OR NULLIF(Target.[my_table_closed_for_spi_date], Source.[my_table_closed_for_spi_date]) IS NOT NULL OR
NULLIF(Source.[my_table_closed_for_money_date], Target.[my_table_closed_for_money_date]) IS NOT NULL OR NULLIF(Target.[my_table_closed_for_money_date], Source.[my_table_closed_for_money_date]) IS NOT NULL OR
NULLIF(Source.[my_table_category], Target.[my_table_category]) IS NOT NULL OR NULLIF(Target.[my_table_category], Source.[my_table_category]) IS NOT NULL OR
NULLIF(Source.[my_table_spread_relationship], Target.[my_table_spread_relationship]) IS NOT NULL OR NULLIF(Target.[my_table_spread_relationship], Source.[my_table_spread_relationship]) IS NOT NULL OR
NULLIF(Source.[my_table_management_charge], Target.[my_table_management_charge]) IS NOT NULL OR NULLIF(Target.[my_table_management_charge], Source.[my_table_management_charge]) IS NOT NULL OR
NULLIF(Source.[my_table_sellout_period_mths], Target.[my_table_sellout_period_mths]) IS NOT NULL OR NULLIF(Target.[my_table_sellout_period_mths], Source.[my_table_sellout_period_mths]) IS NOT NULL OR
NULLIF(Source.[my_table_currency], Target.[my_table_currency]) IS NOT NULL OR NULLIF(Target.[my_table_currency], Source.[my_table_currency]) IS NOT NULL OR
NULLIF(Source.[my_table_price_tolerance], Target.[my_table_price_tolerance]) IS NOT NULL OR NULLIF(Target.[my_table_price_tolerance], Source.[my_table_price_tolerance]) IS NOT NULL OR
NULLIF(Source.[my_table_initial_price_date], Target.[my_table_initial_price_date]) IS NOT NULL OR NULLIF(Target.[my_table_initial_price_date], Source.[my_table_initial_price_date]) IS NOT NULL OR
NULLIF(Source.[my_table_last_date_in_period], Target.[my_table_last_date_in_period]) IS NOT NULL OR NULLIF(Target.[my_table_last_date_in_period], Source.[my_table_last_date_in_period]) IS NOT NULL OR
NULLIF(Source.[my_table_sell_last_date_in_period], Target.[my_table_sell_last_date_in_period]) IS NOT NULL OR NULLIF(Target.[my_table_sell_last_date_in_period], Source.[my_table_sell_last_date_in_period]) IS NOT NULL OR
NULLIF(Source.[my_table_last_day_in_period], Target.[my_table_last_day_in_period]) IS NOT NULL OR NULLIF(Target.[my_table_last_day_in_period], Source.[my_table_last_day_in_period]) IS NOT NULL OR
NULLIF(Source.[my_table_sell_last_day_in_period], Target.[my_table_sell_last_day_in_period]) IS NOT NULL OR NULLIF(Target.[my_table_sell_last_day_in_period], Source.[my_table_sell_last_day_in_period]) IS NOT NULL OR
NULLIF(Source.[my_table_same_day_in_period], Target.[my_table_same_day_in_period]) IS NOT NULL OR NULLIF(Target.[my_table_same_day_in_period], Source.[my_table_same_day_in_period]) IS NOT NULL OR
NULLIF(Source.[my_table_sell_same_day_in_period], Target.[my_table_sell_same_day_in_period]) IS NOT NULL OR NULLIF(Target.[my_table_sell_same_day_in_period], Source.[my_table_sell_same_day_in_period]) IS NOT NULL OR
NULLIF(Source.[my_table_use_working_days], Target.[my_table_use_working_days]) IS NOT NULL OR NULLIF(Target.[my_table_use_working_days], Source.[my_table_use_working_days]) IS NOT NULL OR
NULLIF(Source.[my_table_external_id], Target.[my_table_external_id]) IS NOT NULL OR NULLIF(Target.[my_table_external_id], Source.[my_table_external_id]) IS NOT NULL OR
NULLIF(Source.[my_table_post_initial_price_date], Target.[my_table_post_initial_price_date]) IS NOT NULL OR NULLIF(Target.[my_table_post_initial_price_date], Source.[my_table_post_initial_price_date]) IS NOT NULL OR
NULLIF(Source.[my_table_price_applies_frequency], Target.[my_table_price_applies_frequency]) IS NOT NULL OR NULLIF(Target.[my_table_price_applies_frequency], Source.[my_table_price_applies_frequency]) IS NOT NULL OR
NULLIF(Source.[my_table_price_country_code], Target.[my_table_price_country_code]) IS NOT NULL OR NULLIF(Target.[my_table_price_country_code], Source.[my_table_price_country_code]) IS NOT NULL OR
NULLIF(Source.[my_table_non_working_price_days_adj], Target.[my_table_non_working_price_days_adj]) IS NOT NULL OR NULLIF(Target.[my_table_non_working_price_days_adj], Source.[my_table_non_working_price_days_adj]) IS NOT NULL OR
NULLIF(Source.[my_table_pricing_calendar], Target.[my_table_pricing_calendar]) IS NOT NULL OR NULLIF(Target.[my_table_pricing_calendar], Source.[my_table_pricing_calendar]) IS NOT NULL OR
NULLIF(Source.[my_table_risk_profile], Target.[my_table_risk_profile]) IS NOT NULL OR NULLIF(Target.[my_table_risk_profile], Source.[my_table_risk_profile]) IS NOT NULL OR
NULLIF(Source.[my_table_pay_dividend], Target.[my_table_pay_dividend]) IS NOT NULL OR NULLIF(Target.[my_table_pay_dividend], Source.[my_table_pay_dividend]) IS NOT NULL OR
NULLIF(Source.[my_table_dividend_frequency], Target.[my_table_dividend_frequency]) IS NOT NULL OR NULLIF(Target.[my_table_dividend_frequency], Source.[my_table_dividend_frequency]) IS NOT NULL OR
NULLIF(Source.[my_table_sedol], Target.[my_table_sedol]) IS NOT NULL OR NULLIF(Target.[my_table_sedol], Source.[my_table_sedol]) IS NOT NULL OR
NULLIF(Source.[my_table_type], Target.[my_table_type]) IS NOT NULL OR NULLIF(Target.[my_table_type], Source.[my_table_type]) IS NOT NULL OR
NULLIF(Source.[my_table_strike_date], Target.[my_table_strike_date]) IS NOT NULL OR NULLIF(Target.[my_table_strike_date], Source.[my_table_strike_date]) IS NOT NULL OR
NULLIF(Source.[my_table_maturity_date], Target.[my_table_maturity_date]) IS NOT NULL OR NULLIF(Target.[my_table_maturity_date], Source.[my_table_maturity_date]) IS NOT NULL OR
NULLIF(Source.[my_table_amc_basis_no], Target.[my_table_amc_basis_no]) IS NOT NULL OR NULLIF(Target.[my_table_amc_basis_no], Source.[my_table_amc_basis_no]) IS NOT NULL OR
NULLIF(Source.[my_table_coupon_select_id], Target.[my_table_coupon_select_id]) IS NOT NULL OR NULLIF(Target.[my_table_coupon_select_id], Source.[my_table_coupon_select_id]) IS NOT NULL OR
NULLIF(Source.[my_table_coupon_defaults], Target.[my_table_coupon_defaults]) IS NOT NULL OR NULLIF(Target.[my_table_coupon_defaults], Source.[my_table_coupon_defaults]) IS NOT NULL OR
NULLIF(Source.[my_table_whole_units], Target.[my_table_whole_units]) IS NOT NULL OR NULLIF(Target.[my_table_whole_units], Source.[my_table_whole_units]) IS NOT NULL OR
NULLIF(Source.[my_table_clone_by_policy], Target.[my_table_clone_by_policy]) IS NOT NULL OR NULLIF(Target.[my_table_clone_by_policy], Source.[my_table_clone_by_policy]) IS NOT NULL OR
NULLIF(Source.[my_table_initial_clone_price], Target.[my_table_initial_clone_price]) IS NOT NULL OR NULLIF(Target.[my_table_initial_clone_price], Source.[my_table_initial_clone_price]) IS NOT NULL OR
NULLIF(Source.[my_table_price_base_calc_date], Target.[my_table_price_base_calc_date]) IS NOT NULL OR NULLIF(Target.[my_table_price_base_calc_date], Source.[my_table_price_base_calc_date]) IS NOT NULL OR
NULLIF(Source.[my_table_group], Target.[my_table_group]) IS NOT NULL OR NULLIF(Target.[my_table_group], Source.[my_table_group]) IS NOT NULL OR
NULLIF(Source.[my_table_disinv_notice_freq], Target.[my_table_disinv_notice_freq]) IS NOT NULL OR NULLIF(Target.[my_table_disinv_notice_freq], Source.[my_table_disinv_notice_freq]) IS NOT NULL OR
NULLIF(Source.[my_table_disinv_notice_value], Target.[my_table_disinv_notice_value]) IS NOT NULL OR NULLIF(Target.[my_table_disinv_notice_value], Source.[my_table_disinv_notice_value]) IS NOT NULL OR
NULLIF(Source.[my_table_disinv_same_day_in_period], Target.[my_table_disinv_same_day_in_period]) IS NOT NULL OR NULLIF(Target.[my_table_disinv_same_day_in_period], Source.[my_table_disinv_same_day_in_period]) IS NOT NULL OR
NULLIF(Source.[my_table_disinv_notice_last_date], Target.[my_table_disinv_notice_last_date]) IS NOT NULL OR NULLIF(Target.[my_table_disinv_notice_last_date], Source.[my_table_disinv_notice_last_date]) IS NOT NULL OR
NULLIF(Source.[my_table_trade_cutoff_freq], Target.[my_table_trade_cutoff_freq]) IS NOT NULL OR NULLIF(Target.[my_table_trade_cutoff_freq], Source.[my_table_trade_cutoff_freq]) IS NOT NULL OR
NULLIF(Source.[my_table_trade_cutoff_value], Target.[my_table_trade_cutoff_value]) IS NOT NULL OR NULLIF(Target.[my_table_trade_cutoff_value], Source.[my_table_trade_cutoff_value]) IS NOT NULL OR
NULLIF(Source.[my_table_trade_cutoff_same_day_in_period], Target.[my_table_trade_cutoff_same_day_in_period]) IS NOT NULL OR NULLIF(Target.[my_table_trade_cutoff_same_day_in_period], Source.[my_table_trade_cutoff_same_day_in_period]) IS NOT NULL OR
NULLIF(Source.[my_table_trade_cutoff_last_date], Target.[my_table_trade_cutoff_last_date]) IS NOT NULL OR NULLIF(Target.[my_table_trade_cutoff_last_date], Source.[my_table_trade_cutoff_last_date]) IS NOT NULL OR
NULLIF(Source.[my_table_expected_delay_rules], Target.[my_table_expected_delay_rules]) IS NOT NULL OR NULLIF(Target.[my_table_expected_delay_rules], Source.[my_table_expected_delay_rules]) IS NOT NULL OR
NULLIF(Source.[my_table_settlement_days], Target.[my_table_settlement_days]) IS NOT NULL OR NULLIF(Target.[my_table_settlement_days], Source.[my_table_settlement_days]) IS NOT NULL OR
NULLIF(Source.[my_table_bid_offer_exception_rules], Target.[my_table_bid_offer_exception_rules]) IS NOT NULL OR NULLIF(Target.[my_table_bid_offer_exception_rules], Source.[my_table_bid_offer_exception_rules]) IS NOT NULL OR
NULLIF(Source.[my_table_holding_fund_id], Target.[my_table_holding_fund_id]) IS NOT NULL OR NULLIF(Target.[my_table_holding_fund_id], Source.[my_table_holding_fund_id]) IS NOT NULL OR
NULLIF(Source.[my_table_timeout_days], Target.[my_table_timeout_days]) IS NOT NULL OR NULLIF(Target.[my_table_timeout_days], Source.[my_table_timeout_days]) IS NOT NULL OR
NULLIF(Source.[my_table_price_valuation_basis], Target.[my_table_price_valuation_basis]) IS NOT NULL OR NULLIF(Target.[my_table_price_valuation_basis], Source.[my_table_price_valuation_basis]) IS NOT NULL OR
NULLIF(Source.[my_table_classification], Target.[my_table_classification]) IS NOT NULL OR NULLIF(Target.[my_table_classification], Source.[my_table_classification]) IS NOT NULL OR
NULLIF(Source.[my_table_target_days], Target.[my_table_target_days]) IS NOT NULL OR NULLIF(Target.[my_table_target_days], Source.[my_table_target_days]) IS NOT NULL OR
NULLIF(Source.[my_table_sell_target_days], Target.[my_table_sell_target_days]) IS NOT NULL OR NULLIF(Target.[my_table_sell_target_days], Source.[my_table_sell_target_days]) IS NOT NULL OR
NULLIF(Source.[my_table_disinv_same_day_period_skip], Target.[my_table_disinv_same_day_period_skip]) IS NOT NULL OR NULLIF(Target.[my_table_disinv_same_day_period_skip], Source.[my_table_disinv_same_day_period_skip]) IS NOT NULL OR
NULLIF(Source.[my_table_trade_cutoff_same_day_period_skip], Target.[my_table_trade_cutoff_same_day_period_skip]) IS NOT NULL OR NULLIF(Target.[my_table_trade_cutoff_same_day_period_skip], Source.[my_table_trade_cutoff_same_day_period_skip]) IS NOT NULL OR
NULLIF(Source.[my_table_equity_sector], Target.[my_table_equity_sector]) IS NOT NULL OR NULLIF(Target.[my_table_equity_sector], Source.[my_table_equity_sector]) IS NOT NULL OR
NULLIF(Source.[my_table_client_classification], Target.[my_table_client_classification]) IS NOT NULL OR NULLIF(Target.[my_table_client_classification], Source.[my_table_client_classification]) IS NOT NULL OR
NULLIF(Source.[my_table_max_decimal_places], Target.[my_table_max_decimal_places]) IS NOT NULL OR NULLIF(Target.[my_table_max_decimal_places], Source.[my_table_max_decimal_places]) IS NOT NULL OR
NULLIF(Source.[my_table_rounding_method], Target.[my_table_rounding_method]) IS NOT NULL OR NULLIF(Target.[my_table_rounding_method], Source.[my_table_rounding_method]) IS NOT NULL OR
NULLIF(Source.[my_table_closing_time], Target.[my_table_closing_time]) IS NOT NULL OR NULLIF(Target.[my_table_closing_time], Source.[my_table_closing_time]) IS NOT NULL OR
NULLIF(Source.[my_table_rounding_direction], Target.[my_table_rounding_direction]) IS NOT NULL OR NULLIF(Target.[my_table_rounding_direction], Source.[my_table_rounding_direction]) IS NOT NULL OR
NULLIF(Source.[my_table_use_external_WS], Target.[my_table_use_external_WS]) IS NOT NULL OR NULLIF(Target.[my_table_use_external_WS], Source.[my_table_use_external_WS]) IS NOT NULL OR
NULLIF(Source.[my_table_gl_code], Target.[my_table_gl_code]) IS NOT NULL OR NULLIF(Target.[my_table_gl_code], Source.[my_table_gl_code]) IS NOT NULL OR
NULLIF(Source.[my_table_asset_class], Target.[my_table_asset_class]) IS NOT NULL OR NULLIF(Target.[my_table_asset_class], Source.[my_table_asset_class]) IS NOT NULL OR
NULLIF(Source.[my_table_grouping], Target.[my_table_grouping]) IS NOT NULL OR NULLIF(Target.[my_table_grouping], Source.[my_table_grouping]) IS NOT NULL OR
NULLIF(Source.[my_table_factsheet_url], Target.[my_table_factsheet_url]) IS NOT NULL OR NULLIF(Target.[my_table_factsheet_url], Source.[my_table_factsheet_url]) IS NOT NULL OR
NULLIF(Source.[my_table_aladdin_ticker], Target.[my_table_aladdin_ticker]) IS NOT NULL OR NULLIF(Target.[my_table_aladdin_ticker], Source.[my_table_aladdin_ticker]) IS NOT NULL OR
NULLIF(Source.[my_table_manager], Target.[my_table_manager]) IS NOT NULL OR NULLIF(Target.[my_table_manager], Source.[my_table_manager]) IS NOT NULL OR
NULLIF(Source.[my_table_use_notice_for_backdates], Target.[my_table_use_notice_for_backdates]) IS NOT NULL OR NULLIF(Target.[my_table_use_notice_for_backdates], Source.[my_table_use_notice_for_backdates]) IS NOT NULL OR
NULLIF(Source.[my_table_business_date_delay], Target.[my_table_business_date_delay]) IS NOT NULL OR NULLIF(Target.[my_table_business_date_delay], Source.[my_table_business_date_delay]) IS NOT NULL OR
NULLIF(Source.[my_table_growth_low], Target.[my_table_growth_low]) IS NOT NULL OR NULLIF(Target.[my_table_growth_low], Source.[my_table_growth_low]) IS NOT NULL OR
NULLIF(Source.[my_table_growth_med], Target.[my_table_growth_med]) IS NOT NULL OR NULLIF(Target.[my_table_growth_med], Source.[my_table_growth_med]) IS NOT NULL OR
NULLIF(Source.[my_table_growth_high], Target.[my_table_growth_high]) IS NOT NULL OR NULLIF(Target.[my_table_growth_high], Source.[my_table_growth_high]) IS NOT NULL OR
NULLIF(Source.[my_table_growth_SMPI], Target.[my_table_growth_SMPI]) IS NOT NULL OR NULLIF(Target.[my_table_growth_SMPI], Source.[my_table_growth_SMPI]) IS NOT NULL OR
NULLIF(Source.[my_table_instruction_file_decimal_places], Target.[my_table_instruction_file_decimal_places]) IS NOT NULL OR NULLIF(Target.[my_table_instruction_file_decimal_places], Source.[my_table_instruction_file_decimal_places]) IS NOT NULL OR
NULLIF(Source.[my_table_suspend_start_date], Target.[my_table_suspend_start_date]) IS NOT NULL OR NULLIF(Target.[my_table_suspend_start_date], Source.[my_table_suspend_start_date]) IS NOT NULL OR
NULLIF(Source.[my_table_suspend_end_date], Target.[my_table_suspend_end_date]) IS NOT NULL OR NULLIF(Target.[my_table_suspend_end_date], Source.[my_table_suspend_end_date]) IS NOT NULL ) THEN
UPDATE SET
[my_table_create_date] = Source.[my_table_create_date],
[my_table_last_updt_date] = Source.[my_table_last_updt_date],
-- All fields listed in order.
[my_table_suspend_end_date] = Source.[my_table_suspend_end_date]
WHEN NOT MATCHED BY TARGET THEN
INSERT([my_table_code],[my_table_create_date],[my_table_last_updt_date],[my_table_last_updt_time],[my_table_last_updt_userid],[my_table_record_status],[my_table_name],[my_table_next_or_last_price],[my_table_pricing_frequency],[my_table_sell_pricing_frequency],[my_table_commenced_date],[my_table_closed_date],[my_table_closed_for_newbus_date],[my_table_closed_for_spi_date],[my_table_closed_for_money_date],[my_table_category],[my_table_spread_relationship],[my_table_management_charge],[my_table_sellout_period_mths],[my_table_currency],[my_table_price_tolerance],[my_table_initial_price_date],[my_table_last_date_in_period],[my_table_sell_last_date_in_period],[my_table_last_day_in_period],[my_table_sell_last_day_in_period],[my_table_same_day_in_period],[my_table_sell_same_day_in_period],[my_table_use_working_days],[my_table_external_id],[my_table_post_initial_price_date],[my_table_price_applies_frequency],[my_table_price_country_code],[my_table_non_working_price_days_adj],[my_table_pricing_calendar],[my_table_risk_profile],[my_table_pay_dividend],[my_table_dividend_frequency],[my_table_sedol],[my_table_type],[my_table_strike_date],[my_table_maturity_date],[my_table_amc_basis_no],[my_table_coupon_select_id],[my_table_coupon_defaults],[my_table_whole_units],[my_table_clone_by_policy],[my_table_initial_clone_price],[my_table_price_base_calc_date],[my_table_group],[my_table_disinv_notice_freq],[my_table_disinv_notice_value],[my_table_disinv_same_day_in_period],[my_table_disinv_notice_last_date],[my_table_trade_cutoff_freq],[my_table_trade_cutoff_value],[my_table_trade_cutoff_same_day_in_period],[my_table_trade_cutoff_last_date],[my_table_expected_delay_rules],[my_table_settlement_days],[my_table_bid_offer_exception_rules],[my_table_holding_fund_id],[my_table_timeout_days],[my_table_price_valuation_basis],[my_table_classification],[my_table_target_days],[my_table_sell_target_days],[my_table_disinv_same_day_period_skip],[my_table_trade_cutoff_same_day_period_skip],[my_table_equity_sector],[my_table_client_classification],[my_table_max_decimal_places],[my_table_rounding_method],[my_table_closing_time],[my_table_rounding_direction],[my_table_use_external_WS],[my_table_gl_code],[my_table_asset_class],[my_table_grouping],[my_table_factsheet_url],[my_table_aladdin_ticker],[my_table_manager],[my_table_use_notice_for_backdates],[my_table_business_date_delay],[my_table_growth_low],[my_table_growth_med],[my_table_growth_high],[my_table_growth_SMPI],[my_table_instruction_file_decimal_places],[my_table_suspend_start_date],[my_table_suspend_end_date])
VALUES(Source.[my_table_code],Source.[my_table_create_date],Source.[my_table_last_updt_date],Source.[my_table_last_updt_time],Source.[my_table_last_updt_userid],Source.[my_table_record_status],Source.[my_table_name],Source.[my_table_next_or_last_price],Source.[my_table_pricing_frequency],Source.[my_table_sell_pricing_frequency],Source.[my_table_commenced_date],Source.[my_table_closed_date],Source.[my_table_closed_for_newbus_date],Source.[my_table_closed_for_spi_date],Source.[my_table_closed_for_money_date],Source.[my_table_category],Source.[my_table_spread_relationship],Source.[my_table_management_charge],Source.[my_table_sellout_period_mths],Source.[my_table_currency],Source.[my_table_price_tolerance],Source.[my_table_initial_price_date],Source.[my_table_last_date_in_period],Source.[my_table_sell_last_date_in_period],Source.[my_table_last_day_in_period],Source.[my_table_sell_last_day_in_period],Source.[my_table_same_day_in_period],Source.[my_table_sell_same_day_in_period],Source.[my_table_use_working_days],Source.[my_table_external_id],Source.[my_table_post_initial_price_date],Source.[my_table_price_applies_frequency],Source.[my_table_price_country_code],Source.[my_table_non_working_price_days_adj],Source.[my_table_pricing_calendar],Source.[my_table_risk_profile],Source.[my_table_pay_dividend],Source.[my_table_dividend_frequency],Source.[my_table_sedol],Source.[my_table_type],Source.[my_table_strike_date],Source.[my_table_maturity_date],Source.[my_table_amc_basis_no],Source.[my_table_coupon_select_id],Source.[my_table_coupon_defaults],Source.[my_table_whole_units],Source.[my_table_clone_by_policy],Source.[my_table_initial_clone_price],Source.[my_table_price_base_calc_date],Source.[my_table_group],Source.[my_table_disinv_notice_freq],Source.[my_table_disinv_notice_value],Source.[my_table_disinv_same_day_in_period],Source.[my_table_disinv_notice_last_date],Source.[my_table_trade_cutoff_freq],Source.[my_table_trade_cutoff_value],Source.[my_table_trade_cutoff_same_day_in_period],Source.[my_table_trade_cutoff_last_date],Source.[my_table_expected_delay_rules],Source.[my_table_settlement_days],Source.[my_table_bid_offer_exception_rules],Source.[my_table_holding_fund_id],Source.[my_table_timeout_days],Source.[my_table_price_valuation_basis],Source.[my_table_classification],Source.[my_table_target_days],Source.[my_table_sell_target_days],Source.[my_table_disinv_same_day_period_skip],Source.[my_table_trade_cutoff_same_day_period_skip],Source.[my_table_equity_sector],Source.[my_table_client_classification],Source.[my_table_max_decimal_places],Source.[my_table_rounding_method],Source.[my_table_closing_time],Source.[my_table_rounding_direction],Source.[my_table_use_external_WS],Source.[my_table_gl_code],Source.[my_table_asset_class],Source.[my_table_grouping],Source.[my_table_factsheet_url],Source.[my_table_aladdin_ticker],Source.[my_table_manager],Source.[my_table_use_notice_for_backdates],Source.[my_table_business_date_delay],Source.[my_table_growth_low],Source.[my_table_growth_med],Source.[my_table_growth_high],Source.[my_table_growth_SMPI],Source.[my_table_instruction_file_decimal_places],Source.[my_table_suspend_start_date],Source.[my_table_suspend_end_date])
WHEN NOT MATCHED BY SOURCE THEN
DELETE
;
GO
DECLARE @mergeError int
, @mergeCount int
SELECT @mergeError = @@ERROR, @mergeCount = @@ROWCOUNT
IF @mergeError != 0
BEGIN
PRINT 'ERROR OCCURRED IN MERGE FOR [my_table]. Rows affected: ' + CAST(@mergeCount AS VARCHAR(100)); -- SQL should always return zero rows affected
END
ELSE
BEGIN
PRINT '[my_table] rows affected by MERGE: ' + CAST(@mergeCount AS VARCHAR(100));
END
GO
EDIT: Хорошо, удалив 2508 строк, он работает в считанные секунды. Я не знаю достаточно о скриптах слияния, чтобы узнать, почему количество строк повлияет на это.