SQL Server 2017 Developer SQL Server 2017 Enterprise SQL Server 2017 Enterprise Core SQL Server 2017 Standard on Windows SQL Server 2017 Standard on Linux SQL Server 2019 on Linux SQL Server 2019 on Windows Еще…Меньше
Проблемы
Предположим, что вы выполняете команду ALTER INDEX REBUILD, которая содержит возобновляемый параметр = on в Microsoft SQL Server. Если это фильтр
Индекс, включающий условие, например Column, имеет значение NULL, операция может завершиться ошибкой и вернуть
Ошибка утверждения. Кроме того, может быть создан файл аварийной копии памяти.
Статус
Корпорация Майкрософт подтверждает наличие этой проблемы в своих продуктах, которые перечислены в разделе «Применяется к».
Решение
Эта проблема устранена в следующем накопительном обновлении SQL Server:
-
Накопительное обновление 6 для SQL Server 2019
-
Накопительное обновление 20 для SQL Server 2017
Примечание. В зависимости от предметного указателя
Структура и фильтрованное условие для индекса, версия SQL Server не может безопасно
полная сборка возобновляемого индекса. После установки SP1 вместо
создавая утверждения и дампы, SQL Server корректно завершает работу
операцию и возвращает новый код ошибки 10675.
«Внутренняя ошибка обработчика запросов: обработчик запросов
не удалось создать план запроса. Возможность возобновления работы не поддерживается для этого
Сборка индекса. Удалите возобновляемый параметр и перезапустите инструкцию. «
Сведения о накопительных обновлениях для SQL Server.
Все новые накопительные обновления для SQL Server содержат все исправления и все исправления для системы безопасности, которые были включены в предыдущий накопительный пакет обновления. Ознакомьтесь с самыми последними накопительными обновлениями для SQL Server.
-
Последнее накопительное обновление для SQL Server 2019
-
Последнее накопительное обновление для SQL Server 2017
Ссылки
L–это терминология, которую корпорация Майкрософт использует для описания обновлений программного обеспечения.
Нужна дополнительная помощь?
Нужны дополнительные параметры?
Изучите преимущества подписки, просмотрите учебные курсы, узнайте, как защитить свое устройство и т. д.
В сообществах можно задавать вопросы и отвечать на них, отправлять отзывы и консультироваться с экспертами разных профилей.
I have a very long query which uses distinct intersect, when the query grows too long and I execute it it throws above exception
SELECT DISTINCT RTypeId FROM dbo.User_Res WHERE UserId = '1749'
INTERSECT SELECT DISTINCT RTypeId FROM dbo.User_Res WHERE UserId = '424'
INTERSECT SELECT DISTINCT RTypeId FROM dbo.User_Res WHERE UserId = '1906'
INTERSECT SELECT DISTINCT RTypeId FROM dbo.User_Res WHERE UserId = '725'
INTERSECT SELECT DISTINCT RTypeId FROM dbo.User_Res WHERE UserId = '1596'
Can you please help me with an alternative to this query?
Error msg:
The query processor ran out of internal resources and could not produce a query plan. This is a rare event and only expected for extremely complex queries or queries that reference a very large number of tables or partitions. Please simplify the query.
marc_s
729k175 gold badges1327 silver badges1455 bronze badges
asked Dec 5, 2013 at 10:13
3
So essentially what you want is to get RTypeIds’ that are common to all the users?
You could build the same query in this way:
with userrt (rid, uid)
as (select distinct rtypeid, userid from User_Res where UserId in (1749, 424, 1906 ...)
select rid, count(uid) as cuid
from userrt
group by rid
Now only those result rows that have cuid == amount of userid’s in limiting clause are the ones you’re interested in (since they’ve been there for all users and are therefore common to all).
answered Dec 5, 2013 at 10:50
Pasi SavolainenPasi Savolainen
2,4401 gold badge22 silver badges35 bronze badges
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
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
Ошибка СУБД: Обработчик запросов исчерпал внутренние ресурсы… |
Я |
Ёхан Палыч
18.01.12 — 06:16
Периодически, не всегда, выдает на формирование ОСВ за год вот такую ошибку:
Ошибка СУБД:
Microsoft OLE DB Provider for QSL Server: Обработчик запросов исчерпал внутренние ресурсы, и ему не удалось предоставить план запроса.
Это редкое событие, которое может происходить только при очень сложных запросах или запросах, которые обращаются к очень большому числу таблиц или секций.
Упростите запрос…
Сервер на базе i5, ОЗУ=8Гб. 64-битный 1С Сервер. SQL 2008.
Как можно лечить? Поможет ли увеличение оперативки?
Rie
1 — 18.01.12 — 06:21
(0) Упрости запрос.
Ёхан Палыч
2 — 18.01.12 — 06:27
(1) бухам нужен ОСВ за год по всем счетам, упрощать не собираются, к тому же он иногда отрабатывает. след. можно как-то лечить
Rie
3 — 18.01.12 — 06:29
(2) Можно разбить запрос на несколько, использовать временные таблицы и т.д.
Ёхан Палыч
4 — 18.01.12 — 06:30
(3) все не то, не полезу я им новый ОСВ писать, мне кажется дело в настройках СКЛ, только что там настроть можно — ума не приложу
Rie
5 — 18.01.12 — 06:35
(4) Попробуй посмотреть, что говорит sp_configure.
Ёхан Палыч
6 — 18.01.12 — 06:36
(5) а что это? я не силен в скл
Rie
7 — 18.01.12 — 06:39
Ёхан Палыч
8 — 18.01.12 — 06:40
(7) ок, посмтрю
Rie
9 — 18.01.12 — 06:41
+(7) Только, IMHO, всё же лучше попробовать упростить запрос. Не переписывая всё, только попробовать слегка оптимизировать. Например, IN (SELECT если есть — заменить на что-нибудь полегче. И вообще подзапросы повыносить во временные таблицы.
Ёхан Палыч
10 — 18.01.12 — 06:47
(9) но иногда же отрабатывает, это наводит на мысль…
Rie
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) ок, попробую
ILM
19 — 18.01.12 — 09:12
(2) Главному или всем? Если всем посылай их подальше. Пусть анализ счета и обороты смотрят по нему. Или список выдают…
ILM
20 — 18.01.12 — 09:14
Из тех счетов что смотреть…
Представляю себе ОСВ, ну очень крупного холдинга ))))
Ёхан Палыч
21 — 18.01.12 — 09:20
(20) главному; нет не холдинг, так себе конторка — это и бесит, какой то ОСВ за год
Evgenich71
22 — 03.02.12 — 13:02
Может быть у пользователя установлены права с ограничением прав на уровне записи?
LanLion
23 — 24.02.12 — 16:14
Полный бред граждане это ошибка платформы 1с, скуля или релиза опять 1сники что-то улучшили, вылезла такая же гадость на днях да последних релизов такого небыло, работало все нормально и разворачивала и разворачивает намного более сложные отчеты. 1с позиционирует себя как ерп и т.д сажает себя на оракл и вытворяет такую ..ерню. Все тут советуют упростить запрос, а тем у кого конфа на поддержке да и вообще какого фига мы должны за них делать их работу это типовой отчет.
- Remove From My Forums
-
Question
-
SQL Server Version: Microsoft SQL Server 2008 (RTM) — 10.0.1600.22 (X64) Jul 9 2008 14:17:44 Copyright (c) 1988-2008 Microsoft Corporation Enterprise Edition (64-bit) on Windows NT 6.0 <X64> (Build 6001: Service Pack 1)
Database Compatibility: 100
We’re receiving this error on one of our sp when created through sqlcmd, but the error goes away when we re-create the sp on SSMS.
Codes on this application is deployed using sqlcmd, is there any settings that we are missing, that causes the error when created on sqlcmd?sp is a a simple sp that does a select/insert/update that utilizes a table variable to hold a query result from a simple inner join query, then uses the values on the table to update different tables.
- Remove From My Forums
-
Question
-
SQL Server Version: Microsoft SQL Server 2008 (RTM) — 10.0.1600.22 (X64) Jul 9 2008 14:17:44 Copyright (c) 1988-2008 Microsoft Corporation Enterprise Edition (64-bit) on Windows NT 6.0 <X64> (Build 6001: Service Pack 1)
Database Compatibility: 100
We’re receiving this error on one of our sp when created through sqlcmd, but the error goes away when we re-create the sp on SSMS.
Codes on this application is deployed using sqlcmd, is there any settings that we are missing, that causes the error when created on sqlcmd?sp is a a simple sp that does a select/insert/update that utilizes a table variable to hold a query result from a simple inner join query, then uses the values on the table to update different tables.
Я бегу следом:
DECLARE @g geography;
declare @point nvarchar(50) =''
declare @i int =0,
@lat decimal(8,6) =0.0,
@long decimal(8,6) =0.0,
@start datetime = getdate()
set @lat =(select (0.9 -Rand()*1.8)*100)
set @long =(select (0.9 -Rand()*1.8)*100)
set @point = (select 'POINT('+CONVERT(varchar(10), @lat)+ ' '
+CONVERT(varchar(10), @long)+')')
SET @g = geography::STGeomFromText(@point, 4326);
SELECT TOP 1000
@lat,
@long,
@g.STDistance(st.[coord]) AS [DistanceFromPoint (in meters)]
, st.[coord]
, st.id
FROM Temp st with(index([SpatialIndex_1]))
этот запрос выполняется плохо, потому что он не использует пространственный индекс, поэтому я добавил with(index([SpatialIndex_1])) чтобы заставить его.
индекс географии выглядит следующим образом:
CREATE SPATIAL INDEX [SpatialIndex_1] ON [dbo].Temp
(
[coord]
)USING GEOGRAPHY_GRID
WITH (GRIDS =(LEVEL_1 = LOW,LEVEL_2 = MEDIUM,LEVEL_3 = LOW,LEVEL_4 = LOW),
CELLS_PER_OBJECT = 16, PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF,
ONLINE = OFF, ALLOW_ROW_LOCKS = OFF, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 95)
ON [PRIMARY]
теперь это дает мне сообщение об ошибке
Msg 8622, Уровень 16, состояние 1, строка 15 процессор запросов не может
предоставить план запроса из-за подсказок, определенных в запросе.
Отправьте запрос без указания каких-либо подсказок и без использования НАБОР
FORCEPLAN.
Я могу читать и понимать, что он говорит мне удалить подсказку, вопрос в том, почему он преуспевает в компиляции, но терпит неудачу во время выполнения? Что-то не так с моим индексом?
что мне нужно изменить для SQL, чтобы начать использовать пространственный индекс?
для генерации некоторых данных вы можете использовать следующий скрипт.
CREATE TABLE dbo.Temp
(
Id int NOT NULL IDENTITY (1, 1),
Coord geography NOT NULL
) ON [PRIMARY]
TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE dbo.Temp ADD CONSTRAINT
PK_Temp PRIMARY KEY CLUSTERED
(
Id
)
WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
ON [PRIMARY]
GO
declare @i int =0
declare @lat decimal(8,6) =0.0
declare @long decimal(8,6) =0.0
while (@i < 47000)
begin
set @lat =(select (0.9 -Rand()*1.8)*100)
set @long =(select (0.9 -Rand()*1.8)*100)
insert into Temp
select geography::Point(@lat, @long,4326)
set @i =@i+1
end
go
CREATE SPATIAL INDEX [SpatialIndex_1] ON [dbo].Temp
(
[coord]
)USING GEOGRAPHY_GRID
WITH (GRIDS =(LEVEL_1 = LOW,LEVEL_2 = MEDIUM,LEVEL_3 = LOW,LEVEL_4 = LOW),
CELLS_PER_OBJECT = 16, PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF,
ALLOW_ROW_LOCKS = OFF, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 95)
ON [PRIMARY]
GO
1 ответов
С здесь:
для использования пространственного индекса в запросе ближайшего соседа должны быть выполнены следующие требования:
- пространственный индекс должен присутствовать на одном из пространственных столбцов и
метод STDistance() должен использовать этот столбец в WHERE и ORDER
По пунктам. - предложение TOP не может содержать оператор PERCENT.
- предложение WHERE должно содержать метод STDistance ().
- если их несколько предикаты в предложении WHERE затем
предикат, содержащий метод STDistance (), должен быть соединен с помощью AND
вместе с другими предикатами. Метод STDistance () не может
быть в необязательной части предложения WHERE. - первое выражение в предложении ORDER BY должно использовать
STDistance() метод. - порядок сортировки для первого выражения STDistance() в порядке по
предложение должно быть ASC. - все строки, для которых STDistance возвращает NULL, должны быть отфильтрованы из.
Так, это должно работать:
DECLARE @g geography;
declare @point nvarchar(50) =''
declare @i int =0,
@lat decimal(8,6) =0.0,
@long decimal(8,6) =0.0,
@start datetime = getdate()
set @lat =(select (0.9 -Rand()*1.8)*100)
set @long =(select (0.9 -Rand()*1.8)*100)
set @point = (select 'POINT('+CONVERT(varchar(10), @lat)+ ' '
+CONVERT(varchar(10), @long)+')')
SET @g = geography::STGeomFromText(@point, 4326);
SELECT TOP 1000
@lat,
@long,
@g.STDistance(st.[coord]) AS [DistanceFromPoint (in meters)]
, st.[coord]
, st.id
FROM Temp st with(index([SpatialIndex_1]))
WHERE @g.STDistance(st.[coord]) IS NOT NULL
ORDER BY @g.STDistance(st.[coord]) asc
вы можете проверить, что он использует пространственный индекс даже WITH INDEX подсказка убирается.
В коде генерируется огромный запрос с множеством методов Where, на что вылетает исключение с текстом:
Обработчику запросов не удалось предоставить план запроса, так как для
этого требуется рабочая таблица, а минимальный размер ее строки
превышает допустимый максимум в 8060 байт. Типичная причина, по
которой требуется рабочая таблица, — наличие в запросе предложений
GROUP BY или ORDER BY. Если в запросе присутствует предложение GROUP
BY или ORDER BY, рассмотрите возможность уменьшения количества или
размера полей в этих предложениях. Рассмотрите возможность
использования префикса (LEFT()) или хэширования (CHECKSUM()) полей для
группирования или префикса для упорядочивания. Однако следует принять
во внимание, что это приведет к изменению поведения запроса.
Подскажите, о чем тут речь и есть ли возможность обойти такое поведение?
Ответы (1 шт):
Если Where используется в linq, попробуй фильтровать информация при подтягивании из БД с помощью регулярных выражений(пример с MongoDriver — не знаю есть ли в Entity Framework):
bsonArray.Add(new BsonDocument("productCode", new BsonDocument("$eq", ProductCode)));
var filter = new BsonDocument("$and", bsonArray);
return _orders.Find(filter).ToList()
Вытягивает информацию по определенному коду товара.
→ Ссылка
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
Ёхан Палыч
18.01.12
✎
06:16
Периодически, не всегда, выдает на формирование ОСВ за год вот такую ошибку:
Ошибка СУБД:
Microsoft OLE DB Provider for QSL Server: Обработчик запросов исчерпал внутренние ресурсы, и ему не удалось предоставить план запроса.
Это редкое событие, которое может происходить только при очень сложных запросах или запросах, которые обращаются к очень большому числу таблиц или секций.
Упростите запрос…
Сервер на базе i5, ОЗУ=8Гб. 64-битный 1С Сервер. SQL 2008.
Как можно лечить? Поможет ли увеличение оперативки?
Rie
18.01.12
✎
06:21
(0) Упрости запрос.
Ёхан Палыч
18.01.12
✎
06:27
(1) бухам нужен ОСВ за год по всем счетам, упрощать не собираются, к тому же он иногда отрабатывает. след. можно как-то лечить
Rie
18.01.12
✎
06:29
(2) Можно разбить запрос на несколько, использовать временные таблицы и т.д.
Ёхан Палыч
18.01.12
✎
06:30
(3) все не то, не полезу я им новый ОСВ писать, мне кажется дело в настройках СКЛ, только что там настроть можно — ума не приложу
Rie
18.01.12
✎
06:35
(4) Попробуй посмотреть, что говорит sp_configure.
Ёхан Палыч
18.01.12
✎
06:36
(5) а что это? я не силен в скл
Rie
18.01.12
✎
06:39
Ёхан Палыч
18.01.12
✎
06:40
(7) ок, посмтрю
Rie
18.01.12
✎
06:41
+(7) Только, IMHO, всё же лучше попробовать упростить запрос. Не переписывая всё, только попробовать слегка оптимизировать. Например, IN (SELECT если есть — заменить на что-нибудь полегче. И вообще подзапросы повыносить во временные таблицы.
Ёхан Палыч
18.01.12
✎
06:47
(9) но иногда же отрабатывает, это наводит на мысль…
Rie
18.01.12
✎
06:51
(10) Оно, конечно, так…
Но если жрёт ресурсы безбожно — то где гарантия, что подкинешь ты ему ресурсов, а оно их снова не сожрёт? Тем более что дальше база будет расти и расти…
Я не настаиваю, посмотри настройки sp_configure — там могут стоять ограничения. Но, IMHO, соптимизировать запрос — обычно полезнее бывает.
упс
18.01.12
✎
07:35
(0) а покажите результат «SELECT @@version»
Ёхан Палыч
18.01.12
✎
08:04
(12) как его показать, я скл не знаю, поставил и работает
пипец
18.01.12
✎
08:10
релиз?
упс
18.01.12
✎
08:13
(13) Подключиться к SQL Server с помощью SQL Server Management Studio, нажать кнопку «New query», ввести SELECT @@version и нажать F5 (либо кнопку Execute)
Ёхан Палыч
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)
упс
18.01.12
✎
08:43
(16) Попробуйте, как вариант, поставить сервиспак — http://support.microsoft.com/kb/2528583
Ёхан Палыч
18.01.12
✎
08:52
(17) ок, попробую
ILM
18.01.12
✎
09:12
(2) Главному или всем? Если всем посылай их подальше. Пусть анализ счета и обороты смотрят по нему. Или список выдают…
ILM
18.01.12
✎
09:14
Из тех счетов что смотреть…
Представляю себе ОСВ, ну очень крупного холдинга ))))
Ёхан Палыч
18.01.12
✎
09:20
(20) главному; нет не холдинг, так себе конторка — это и бесит, какой то ОСВ за год
Evgenich71
03.02.12
✎
13:02
Может быть у пользователя установлены права с ограничением прав на уровне записи?
LanLion
24.02.12
✎
16:14
Полный бред граждане это ошибка платформы 1с, скуля или релиза опять 1сники что-то улучшили, вылезла такая же гадость на днях да последних релизов такого небыло, работало все нормально и разворачивала и разворачивает намного более сложные отчеты. 1с позиционирует себя как ерп и т.д сажает себя на оракл и вытворяет такую ..ерню. Все тут советуют упростить запрос, а тем у кого конфа на поддержке да и вообще какого фига мы должны за них делать их работу это типовой отчет.
|
Антон Курилов 2 / 2 / 0 Регистрация: 19.06.2018 Сообщений: 39 |
||||||||
|
1 |
||||||||
Отображение данных08.02.2023, 08:57. Показов 977. Ответов 25 Метки нет (Все метки)
Добрый день.
Как вариант я вижу столбец с водителем преобразовать в строку
Но как это всё привязать к основному запросу?
0 |
|
88 / 86 / 30 Регистрация: 14.10.2022 Сообщений: 349 |
|
|
08.02.2023, 09:30 |
2 |
|
Совершенно непонятно, чего хотите то получить в итоге.
0 |
|
Антон Курилов 2 / 2 / 0 Регистрация: 19.06.2018 Сообщений: 39 |
||||
|
08.02.2023, 11:20 [ТС] |
3 |
|||
|
мне нужно в запросе указать всех сотрудников участвующих в поездке. Их может быть 1 а может 5. но у меня получается показать только одного.
привязать таблицу сотрудники вот так выглядит в программе а мне нужно сделать простую табличку, что бы было понятно, когда кто и с кем едет, что бы было видно всех сотрудников участвующих в поездке
0 |
|
2 / 2 / 0 Регистрация: 19.06.2018 Сообщений: 39 |
|
|
08.02.2023, 14:33 [ТС] |
4 |
|
Задача написать запрос для получения вот такой таблицы Что бы было видно всех сотрудников участвующих в поездке
0 |
|
1608 / 1117 / 165 Регистрация: 23.07.2010 Сообщений: 6,484 |
|
|
15.02.2023, 11:21 |
5 |
|
так тебе походу left join нужен
0 |
|
Антон Курилов 2 / 2 / 0 Регистрация: 19.06.2018 Сообщений: 39 |
||||
|
15.02.2023, 11:50 [ТС] |
6 |
|||
|
Привет. Согласен. Исправил.
Но тогда все равно видно только одного сотрудника, а если их три-пять?
0 |
|
uaggster 88 / 86 / 30 Регистрация: 14.10.2022 Сообщений: 349 |
||||||||
|
15.02.2023, 12:09 |
7 |
|||||||
|
РешениеВерсия сервера — какая?
Добавлено через 8 минут
1 |
|
2 / 2 / 0 Регистрация: 19.06.2018 Сообщений: 39 |
|
|
15.02.2023, 12:19 [ТС] |
8 |
|
версия sql 2008.
0 |
|
5157 / 4110 / 1031 Регистрация: 29.08.2013 Сообщений: 26,087 Записей в блоге: 3 |
|
|
15.02.2023, 12:35 |
9 |
|
а если запрос который делает сама программа профайлером выдернуть?
0 |
|
2 / 2 / 0 Регистрация: 19.06.2018 Сообщений: 39 |
|
|
15.02.2023, 12:44 [ТС] |
10 |
|
Не совсем понял о чем речь
0 |
|
uaggster 88 / 86 / 30 Регистрация: 14.10.2022 Сообщений: 349 |
||||
|
15.02.2023, 13:23 |
11 |
|||
|
Второй запрос пытался, что то выполнить но выдал ошибку Сделайте
И покажите результат здесь.
0 |
|
2 / 2 / 0 Регистрация: 19.06.2018 Сообщений: 39 |
|
|
15.02.2023, 13:36 [ТС] |
12 |
|
Вот
0 |
|
2 / 2 / 0 Регистрация: 19.06.2018 Сообщений: 39 |
|
|
15.02.2023, 14:57 [ТС] |
14 |
|
На SQl Server 2014 Работает! Спасибо огромное! буду пробовать обновлять свой Sql 2008. Подскажи пожалуйста почему
0 |
|
88 / 86 / 30 Регистрация: 14.10.2022 Сообщений: 349 |
|
|
15.02.2023, 15:13 |
15 |
|
почему в поле sotr нет первого символа. Все фамилии у первого сотрудника начинаются со второй буквы Прошу прощения Добавлено через 1 минуту Или или, короче.
0 |
|
1608 / 1117 / 165 Регистрация: 23.07.2010 Сообщений: 6,484 |
|
|
15.02.2023, 16:24 |
16 |
|
INNER JOIN вот это не смущает?
0 |
|
2 / 2 / 0 Регистрация: 19.06.2018 Сообщений: 39 |
|
|
16.02.2023, 06:39 [ТС] |
17 |
|
Добрый день. Установил на SQL Server вроде как все обновления.
0 |
|
uaggster 88 / 86 / 30 Регистрация: 14.10.2022 Сообщений: 349 |
||||
|
16.02.2023, 10:32 |
18 |
|||
|
РешениеЭэээ… А вот так — будет работать?
1 |
|
Антон Курилов 2 / 2 / 0 Регистрация: 19.06.2018 Сообщений: 39 |
||||
|
16.02.2023, 12:51 [ТС] |
19 |
|||
|
Всё работает! спасибо огромное! Вы гений! Добавлено через 1 час 58 минут
0 |
|
88 / 86 / 30 Регистрация: 14.10.2022 Сообщений: 349 |
|
|
16.02.2023, 12:58 |
20 |
|
Подскажи пожалуйста как вставить выборку по дате base.data_p ? Вот сейчас не понятно!
0 |
|
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
16.02.2023, 12:58 |
|
20 |

Сообщение было отмечено Антон Курилов как решение

