Ошибка субд внутренняя ошибка обработчика запросов

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.

Md Haidar Ali Khan's user avatar

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's user avatar

Paul WhitePaul 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 Alan's user avatar

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

kilkfoe's user avatar

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's user avatar

Kin Shah

61.6k5 gold badges115 silver badges235 bronze badges

answered Apr 25, 2013 at 21:11

Richard Schweiger's user avatar

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.

Md Haidar Ali Khan's user avatar

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's user avatar

Paul WhitePaul 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 Alan's user avatar

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

kilkfoe's user avatar

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's user avatar

Kin Shah

61.6k5 gold badges115 silver badges235 bronze badges

answered Apr 25, 2013 at 21:11

Richard Schweiger's user avatar

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 ответов


С здесь:

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

  1. пространственный индекс должен присутствовать на одном из пространственных столбцов и
    метод STDistance() должен использовать этот столбец в WHERE и ORDER
    По пунктам.
  2. предложение TOP не может содержать оператор PERCENT.
  3. предложение WHERE должно содержать метод STDistance ().
  4. если их несколько предикаты в предложении WHERE затем
    предикат, содержащий метод STDistance (), должен быть соединен с помощью AND
    вместе с другими предикатами. Метод STDistance () не может
    быть в необязательной части предложения WHERE.
  5. первое выражение в предложении ORDER BY должно использовать
    STDistance() метод.
  6. порядок сортировки для первого выражения STDistance() в порядке по
    предложение должно быть ASC.
  7. все строки, для которых 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.

Md Haidar Ali Khan's user avatar

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's user avatar

Paul WhitePaul 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 Alan's user avatar

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

kilkfoe's user avatar

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's user avatar

Kin Shah

61.6k5 gold badges115 silver badges235 bronze badges

answered Apr 25, 2013 at 21:11

Richard Schweiger's user avatar

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.

Md Haidar Ali Khan's user avatar

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's user avatar

Paul WhitePaul 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 Alan's user avatar

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

kilkfoe's user avatar

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's user avatar

Kin Shah

61.6k5 gold badges115 silver badges235 bronze badges

answered Apr 25, 2013 at 21:11

Richard Schweiger's user avatar

0

   progaoff

18.09.18 — 10:05

Microsoft SQL Server Native Client 11.0: Внутренняя ошибка обработчика запросов: обработчик запросов обнаружил непредвиденную ошибку во время выполнения (HRESULT = 0x80040e19).

HRESULT=80040E14, SQLSrvr: SQLSTATE=42000, state=1, Severity=10, native=8630, line=1

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

Кто сталкивался, может знаете как лечится?

Доброго времени! помогите с ошибкой СУБД, есть 1С 8.1, работает в файл-серверном режиме, СУБД MS SQL 2008 R2 Выполняю этот код: при этом такая ошибка: Microsoft OLE DB Provider for SQL Server: внутренняя ошибка обработчика запросов: обработчик запросов обнаружил непредвиденную ошибку во время выполнения. HRESULT=80040E14 SQLSrv: Error state=1, Severity=10, Native=8630, line=1

>>>работает в файл-серверном режиме это на баш можно….

вот видишь, даже скуль противится непосредственному удалению доков

буквально позавчера все работало)

и снова здрасьте! а такое почему?

хорошо, я чайнег, место на диске у меня закончилось, но вот забава база сама на SQL растет от 29 Гб до 86 Гб зачем, не понятно, модель простая как этого избежать?

настрой в регламенте скуля шринк базы и лога

А что именно «растет», данные или лог?

Тэги: 1С 8

Комментарии доступны только авторизированным пользователям

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.

Md Haidar Ali Khan's user avatar

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's user avatar

Paul WhitePaul 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 Alan's user avatar

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

kilkfoe's user avatar

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's user avatar

Kin Shah

61.6k5 gold badges115 silver badges235 bronze badges

answered Apr 25, 2013 at 21:11

Richard Schweiger's user avatar

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.

Md Haidar Ali Khan's user avatar

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's user avatar

Paul WhitePaul 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 Alan's user avatar

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

kilkfoe's user avatar

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's user avatar

Kin Shah

61.6k5 gold badges115 silver badges235 bronze badges

answered Apr 25, 2013 at 21:11

Richard Schweiger's user avatar

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 ответов


С здесь:

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

  1. пространственный индекс должен присутствовать на одном из пространственных столбцов и
    метод STDistance() должен использовать этот столбец в WHERE и ORDER
    По пунктам.
  2. предложение TOP не может содержать оператор PERCENT.
  3. предложение WHERE должно содержать метод STDistance ().
  4. если их несколько предикаты в предложении WHERE затем
    предикат, содержащий метод STDistance (), должен быть соединен с помощью AND
    вместе с другими предикатами. Метод STDistance () не может
    быть в необязательной части предложения WHERE.
  5. первое выражение в предложении ORDER BY должно использовать
    STDistance() метод.
  6. порядок сортировки для первого выражения STDistance() в порядке по
    предложение должно быть ASC.
  7. все строки, для которых 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.

Md Haidar Ali Khan's user avatar

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's user avatar

Paul WhitePaul 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 Alan's user avatar

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

kilkfoe's user avatar

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's user avatar

Kin Shah

61.6k5 gold badges115 silver badges235 bronze badges

answered Apr 25, 2013 at 21:11

Richard Schweiger's user avatar

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.

Md Haidar Ali Khan's user avatar

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's user avatar

Paul WhitePaul 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 Alan's user avatar

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

kilkfoe's user avatar

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's user avatar

Kin Shah

61.6k5 gold badges115 silver badges235 bronze badges

answered Apr 25, 2013 at 21:11

Richard Schweiger's user avatar

0

I have the following query which runs in Sql Server 2008, it works well if data is small but when it is huge i am getting the exception. Is there any way i can optimize the query

select
        distinct olu.ID
            from olu_1 (nolock) olu

            join mystat (nolock) s
                on s.stat_int = olu.stat_int

            cross apply
                dbo.GetFeeds 
                        (
                                s.stat_id,
                                olu.cha_int, 
                                olu.odr_int,  
                                olu.odr_line_id, 
                                olu.ID
                        ) channels

            join event_details (nolock) fed
                on fed.air_date = olu.intended_air_date
                and fed.cha_int = channels.cha_int
                and fed.break_code_int = olu.break_code_int

            join formats (nolock) fmt
                on fed.format_int = fmt.format_int


            where
                fed.cha_int in (125, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 35, 36, 37, 38, 39, 40, 41, 43, 117, 45, 42, 44, 47, 49, 50, 51, 46, 52, 53, 54, 55, 56, 48, 59, 60, 57, 63, 58, 62, 64, 66, 69, 68, 67, 65, 70, 73, 71, 74, 72, 75, 76, 77, 78, 79, 82, 80, 159, 160, 161, 81, 83, 84, 85, 88, 87, 86, 89, 90, 61, 91, 92, 93, 95, 96, 97, 98, 99, 100, 94, 155, 156, 157, 158, 103, 104, 102, 101, 105, 106, 107, 108, 109, 110, 119, 111, 167, 168, 169, 112, 113, 114, 115, 116, 170, 118, 120, 121, 122, 123, 127, 162, 163, 164, 165, 166, 128, 129, 130, 124, 133, 131, 132, 126, 134, 136, 135, 137, 171, 138, 172, 173, 174) and
                fed.air_date between '5/27/2013 12:00:00 AM' and '6/2/2013 12:00:00 AM' and

                fmt.cha_int in (125, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 35, 36, 37, 38, 39, 40, 41, 43, 117, 45, 42, 44, 47, 49, 50, 51, 46, 52, 53, 54, 55, 56, 48, 59, 60, 57, 63, 58, 62, 64, 66, 69, 68, 67, 65, 70, 73, 71, 74, 72, 75, 76, 77, 78, 79, 82, 80, 159, 160, 161, 81, 83, 84, 85, 88, 87, 86, 89, 90, 61, 91, 92, 93, 95, 96, 97, 98, 99, 100, 94, 155, 156, 157, 158, 103, 104, 102, 101, 105, 106, 107, 108, 109, 110, 119, 111, 167, 168, 169, 112, 113, 114, 115, 116, 170, 118, 120, 121, 122, 123, 127, 162, 163, 164, 165, 166, 128, 129, 130, 124, 133, 131, 132, 126, 134, 136, 135, 137, 171, 138, 172, 173, 174) and
                fmt.air_date between '5/27/2013 12:00:00 AM' and '6/2/2013 12:00:00 AM' 

  • Ошибка субд внутренняя ошибка компоненты dbeng8 как исправить
  • Ошибка субд недопустимое имя объекта params
  • Ошибка субд xx001 error invalid page in block
  • Ошибка субд не удалось найти объект
  • Ошибка субд не удалось выделить новую страницу для базы данных