Обновлено 12.11.2017
добрый день уважаемые читатели блога pyatilistnik.org, у меня на работе по исторически сложившейся ситуации, досталась в наследство одна архаичная служба СКУД Quest 2, кто не в курсе, это очень старая программа по организации системы прохода в компании, по типу СФИНКС. Все это хорошо, но в какой-то момент у меня появилась ошибка «Could not allocate space for object because the ‘PRIMARY’ filegroup is full» не дающая мне ни записывать карточки, ни что либо удалять. Давайте посмотрим как это решается и как это поправить.
Вот как выглядит данная ошибка:
При выполнении операции произошло следующее исключение: Could not allocate space for object ‘Events’ in database ‘Quest’, because the ‘PRIMARY’ filegroup is full
Через какое-то время вообще программа Quesr 2 перестала запускаться.
При выполнении операции произошло следующее исключение» Журнал событий переполнен.
Начав разбираться я обнаружил, что данная утилита, древняя как мамонт, и ее база данных построена на базе MS SQL 2000, да да, ей 17 лет. Размер базы данных оказался 1,8 ГБ.
Исправление ошибки
Если перевести первую ошибку, то видно, что забилась одна из таблиц базы данных, для того, чтобы попасть в базу нам потребуется установить, бесплатный модуль управления SQL Server Management Studio. Как он устанавливается, читаем по ссылке слева. Запускаем его, далее вам необходимо открыть все имеющиеся таблицы, в моем случае это Quest, а в ней уже Events. Щелкните по ней правым кликом и выберите пункт «Открыть таблицу». В результате чего вы увидите общее количество строк в ней.
Как очистить таблицу MS SQL
Давайте теперь вычистим таблицу и восстановим работу нашего СКУД Quest 2. Нам помогут две команды, полностью чистящие таблицу от всех записей.
либо
Если у вас объем таблицы в базе данных SQL большой, то выполнение запроса может занять некоторое время. Отличие truncate от delete, в том, что первый не ведет лог обработки. Надеюсь вам это помогло решить ошибку: Could not allocate space for object because the ‘PRIMARY’ filegroup is full.
In this article, we are going to understand SQL Server error: The Primary filegroup is full and how we can fix this error.
The database administrators must keep track of the database growth. Also, they must do the capacity planning and space management according to the growth and utilization of the database. When we create a new database, we set the value of the max size parameter to UNLIMITED most of the time. However, sometimes due to business requirements and hardware constraints, we are forced to keep the value of the MAXSIZE parameter to a specific value.
When we set the value of the MAXSIZE parameter limited to a specific value, we might encounter the Primary filegroup is full error. This error also occurs when we are using the SQL Server express edition. The maximum allowed size of the database in SQL Server Express edition is 10GB. When the database tries to grow beyond 10GB, the user will encounter the Primary filegroup is full error.
To understand the concept and error, we must create a demo setup with a specific configuration. I have created a database named DemoDatabase, and the size of the database is 40MB. Run the following query to create the database.
CREATE DATABASE [DemoDatabase] ON (NAME = N‘DemoDatabase’, FILENAME = N‘C:MS_SQLDataDemoDatabase.mdf’ , SIZE = 2048KB , MAXSIZE = 20480KB ) LOG ON (NAME = N‘DemoDatabase_log’, FILENAME = N‘C:MS_SQLLogDemoDatabase_log.ldf’ , SIZE = 2048KB , MAXSIZE = 20480KB ) GO |
In the database, we are creating a table named tblFilgroup in the DemoDatabase. The table contains two columns named first_name and address. The datatype of the first_name column is varchar(500) and the datatype of the address column is char(8000). Execute the following query to create the tblFilgroup table.
USE [DemoDatabase] GO CREATE TABLE tblFilegroup(first_name varchar(500), Address char(8000)) GO |
Once the table is created, we are inserting some demo records in the tblFilgroup table. We are inserting 5000 rows in the table. To insert 5000 records, we can use GO 5000 keywords at the end of the insert query. Execute the following query to insert the records.
INSERT INTO tblFilegroup VALUES (‘Nisarg’,‘AB-14, Akshardham Flats, Urban bank road, mehsana’) GO 5000 |
During the execution of the INSERT query, we encounter the following error.
Msg 1105, Level 17, State 2, Line 18
Could not allocate space for object ‘dbo.tblFilegroup’ in database ‘DemoDatabase’ because the ‘PRIMARY’ filegroup is full.
Create disk space by deleting unneeded files, dropping objects in the filegroup, adding additional files to the filegroup, or setting autogrowth on for existing files in the filegroup.
Screenshot:
To identify the root cause, first, let us check the available disk space in the workstation. Run the following command in the PowerShell.
Get—WmiObject —Class Win32_logicaldisk —Filter «DriveType = ‘3’» | Select—Object —Property DeviceID, DriveType, VolumeName, @{L=‘AvailableSpace’;E={«{0:N2}» —f ($_.FreeSpace /1GB)}}, @{L=«TotalDiskSize»;E={«{0:N2}» —f ($_.Size/1GB)}} |
Command Output:
As you can see in the above image, sufficient space is available in the workstation. Now, let us see the value of the MAXSIZE parameter of DemoDatabase. We can query the sys.master_files DMV to review the Autogrowth and max size values of the DemoDatabase. Run the following query.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
SELECT databases.name AS [Database Name], materfiles.type_desc AS [File Type], CAST( (materfiles.Size * 8 ) / 1024.0 AS DECIMAL(18, 1)) AS [Initial Size (MB)], ‘By ‘+IIF( materfiles.is_percent_growth = 1, CAST(materfiles.growth AS VARCHAR(10))+‘%’, CONVERT(VARCHAR(30), CAST( (materfiles.growth * 8 ) / 1024.0 AS DECIMAL(18, 1)))+‘ MB’) AS [Autogrowth], IIF(materfiles.max_size = 0, ‘No growth is allowed’, IIF(materfiles.max_size = —1, ‘Unlimited’, CAST( ( CAST(materfiles.max_size AS BIGINT) * 8 ) / 1024 AS VARCHAR(30))+‘ MB’)) AS [MaximumSize] FROM sys.master_files AS materfiles INNER JOIN sys.databases AS databases ON databases.database_id = materfiles.database_id where databases.name=‘DemoDatabase’ |
Output
As you can in the above image, the value of the Autogrowth parameter for the data file is 12MB and the log file is 18MB. The maximum allowed size of the data and log file is set to 20MB. To resolve this issue, we can increase the value of the MAXSIZE parameter or set the value to UNLIMITED. In our case, we are going to set the value of the MAXSIZE parameter to UNLIMITED. We can change the values by using any of the following methods.
- Change value using SQL Server Management Studio (SSMS)
- ALTER DATABASE command
First, let us change the value using SQL Server management studio. Launch SQL Server Management Studio -> Connect to the SQL Server instance -> Expand Databases Right-click on DemoDatabase and click on Properties.
First, we will change the MAXSIZE of data files. To do that, click on Files. In the right pane, click on a balloon in the Autogrowth / Maxsize column in ROWS File Type.
A dialog box named Change Autogrowth for DemoDatabase opens. In the dialog box, set Maximum File Size to Unlimited. Click on OK to save the value and close the dialog box.
Similarly, change the value of the MAXSIZE parameter of the log files. Once parameter values are updated, click OK to close the database properties.
Alternatively, we can use the ALTER DATABASE statement to change the values of the MAXSIZE parameter. To change the MAXSIZE parameter, the syntax of the ALTER DATABASE statement is the following.
ALTER DATABASE [DB_NAME] MODIFY FILE (LOGICAL_FILENAME, FILEGROWTH= VALUE_IN_KB|UNLIMITED) |
We want to set the value MAXSIZE parameter of the data and log files of the Demodatabase to UNLIMITED. To do that, run the following query.
USE [master] GO ALTER DATABASE [DemoDatabase] MODIFY FILE ( NAME = N‘DemoDatabase’, MAXSIZE = UNLIMITED) GO ALTER DATABASE [DemoDatabase] MODIFY FILE ( NAME = N‘DemoDatabase_log’, MAXSIZE = UNLIMITED) GO |
Once the query is executed successfully, run the below query against sys.master_files DMV.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
SELECT databases.name AS [Database Name], materfiles.type_desc AS [File Type], CAST( (materfiles.Size * 8 ) / 1024.0 AS DECIMAL(18, 1)) AS [Initial Size (MB)], ‘By ‘+IIF( materfiles.is_percent_growth = 1, CAST(materfiles.growth AS VARCHAR(10))+‘%’, CONVERT(VARCHAR(30), CAST( (materfiles.growth * 8 ) / 1024.0 AS DECIMAL(18, 1)))+‘ MB’) AS [Autogrowth], IIF(materfiles.max_size = 0, ‘No growth is allowed’, IIF(materfiles.max_size = —1, ‘-1’, CAST( ( CAST(materfiles.max_size AS BIGINT) * 8 ) / 1024 AS VARCHAR(30))+‘ MB’)) AS [MaximumSize] FROM sys.master_files AS materfiles INNER JOIN sys.databases AS databases ON databases.database_id = materfiles.database_id where databases.name=‘DemoDatabase’ |
Output:
As you can see, the value of the MAXSIZE parameter is -1. According to the Microsoft document, when the MAXSIZE parameter value is -1, the data file can grow until the disk is full.
Now, run the following INSERT statement to insert 5000 records. As we have set the value of the MAXSIZE parameter to UNLIMITED, the records will be inserted successfully.
SET NOCOUNT ON GO INSERT INTO tblFilegroup VALUES (‘Nisarg’,‘AB-14, Akshardham Flats, Urban bank road, mehsana’) GO 5000 |
Output.
As you can see in the above image, the primary filegroup is full error has been resolved and the query inserted 5000 records in the tblFilgroup table successfully.
Summary
In this article, I have explained about the primary filegroup is full error and how to resolve the error. I have also demonstrated a use case to explain when this error can occur and how to fix it and make the database operational.
- Author
- Recent Posts
Nisarg Upadhyay is a SQL Server Database Administrator and Microsoft certified professional who has more than 8 years of experience with SQL Server administration and 2 years with Oracle 10g database administration.
He has expertise in database design, performance tuning, backup and recovery, HA and DR setup, database migrations and upgrades. He has completed the B.Tech from Ganpat University. He can be reached on nisargupadhyay87@outlook.com
I have a very large table in my database and I am starting to get this error
Could not allocate a new page for
database ‘mydatabase’ because of
insufficient disk space in filegroup
‘PRIMARY’. Create the necessary space
by dropping objects in the filegroup,
adding additional files to the
filegroup, or setting autogrowth on
for existing files in the filegroup.
How do you fix this error? I don’t understand the suggestions there.
Nisarg Upadhyay is a SQL Server Database Administrator and Microsoft certified professional who has more than 8 years of experience with SQL Server administration and 2 years with Oracle 10g database administration.
He has expertise in database design, performance tuning, backup and recovery, HA and DR setup, database migrations and upgrades. He has completed the B.Tech from Ganpat University. He can be reached on nisargupadhyay87@outlook.com
I have a very large table in my database and I am starting to get this error
Could not allocate a new page for
database ‘mydatabase’ because of
insufficient disk space in filegroup
‘PRIMARY’. Create the necessary space
by dropping objects in the filegroup,
adding additional files to the
filegroup, or setting autogrowth on
for existing files in the filegroup.
How do you fix this error? I don’t understand the suggestions there.
marc_s
729k174 gold badges1327 silver badges1455 bronze badges
asked Jun 7, 2010 at 7:01
If you’re using SQL Express you may be hitting the maximum database size limit (or more accurately the filegroup size limit) which is 4GB for versions up to 2005, 10GB for SQL Express 2008 onwards. That size limit excludes the log file.
answered Dec 6, 2013 at 10:57
tomRedoxtomRedox
27.7k24 gold badges117 silver badges152 bronze badges
1
There isn’t really much to add — it pretty much tells you what you need to do in the error message.
Each object (Table, SP, Index etc) you create in SQL is created on a filegroup. The default filegroup is PRIMARY. It is common to create multiple filegroups that span over many disks. For instance you could have a filegroup named INDEXES to store all of your Indexes. Or if you have one very large table you could move this on to a different filegroup.
You can allocate space to a filegroup, say 2GB. If Auto Grow is not enabled once the data in the filegroup reaches 2GB SQL Server cannot create any more objects. This will also occur is the disk that the filegroup resides on runs out of space.
I’m not really sure what else to add — as I said previously, the error message pretty much tells you what is required.
answered Jun 7, 2010 at 7:08
codingbadgercodingbadger
42.3k13 gold badges94 silver badges109 bronze badges
If you are using client tools (MSDE) then the data in the filegroup reaches 2GB, SQL Server cannot create any more objects.
answered Feb 12, 2013 at 6:28
Use DBCC shrinkfile statement to shrink file…
USE databasename ;
GO
-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE databasename
SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE (databasename_Log, 1);
GO
-- Reset the database recovery model.
ALTER DATABASE databasename
SET RECOVERY FULL;
GO
mattcan
54012 silver badges30 bronze badges
answered Jun 7, 2010 at 7:20
HarendraHarendra
2493 silver badges10 bronze badges
1
|
|||
J_Silver
24.09.08 — 11:09 |
УТ 10.3.3. Скуль. При обновлении конфигурации БД выдает ошибку
Каталог не обнаружен ‘v8srvr://server/dbase/configsave/d27921ca-6c64-46db-a20c-e30d84e2c08b.0’ Вроде спасает выгрузказагрузка базы. Но может кто подскажет, как еще решить проблему? |
||
Salvador Limones
1 — 24.09.08 — 11:10 |
Чего тебе непонятно здесь — ‘PRIMARY’ filegroup is full ? |
||
ДенисЧ
2 — 24.09.08 — 11:10 |
«because the ‘PRIMARY’ filegroup is full.» |
||
ktif
3 — 24.09.08 — 11:13 |
(2) солдатов насмотрелся?:) |
||
ДенисЧ
4 — 24.09.08 — 11:17 |
(3) Нет, админов настроился… |
||
J_Silver
5 — 24.09.08 — 11:53 |
Извиняюсь, мало опыта работы со скульными базами. |
||
ДенисЧ
6 — 24.09.08 — 11:57 |
(5). А если серьёзно, для начала проверяй место на диске. |
||
Serg_1960
7 — 24.09.08 — 12:19 |
(6) Ну, Денис, — спасибо за «описание» процесса взаимодействия с SQL :)) Я давно уже догадывался что между мной и SQL-сервером «что-то еще нехватает» — а это «что-то» оказывается админом называется :о) |
||
J_Silver
8 — 24.09.08 — 14:28 |
Место 146 ГБ. |
||
ДенисЧ
9 — 24.09.08 — 14:33 |
«or setting autogrowth on for existing files in the filegroup» |
||
J_Silver
10 — 24.09.08 — 14:38 |
Windows server 2003. |
||
Salvador Limones
11 — 24.09.08 — 14:41 |
Версия скуля какая? |
||
J_Silver
12 — 24.09.08 — 14:43 |
Файловая система NTFS.
(9)Говорю ж в настройках SQL server не силен. |
||
Salvador Limones
13 — 24.09.08 — 14:44 |
(12) Express Edition — еще вопросы есть? |
||
ДенисЧ
14 — 24.09.08 — 14:44 |
(12) менеджмент студио — база данных — свойства — файлы. |
||
ДенисЧ
15 — 24.09.08 — 14:45 |
(13) Упс. Не заметил… |
||
Immortal
16 — 24.09.08 — 14:47 |
хых |
||
J_Silver
17 — 24.09.08 — 14:48 |
Вот блин. Проверил. Как раз вырасло на 4 гб. |
||
ДенисЧ
18 — 24.09.08 — 14:48 |
(17) читай (15). У полного ограничений как раз нет. |
||
J_Silver 19 — 24.09.08 — 14:51 |
Спасибо огромное. |
Я в одной книжке по программированию как то прочитал: «Есть два вида языков, одни постоянно ругают, а вторыми никто не пользуется.»
Для выполнения данной инструкции на сервере должна быть установлена утилита SQL Server Management Studio.
Возникновение ошибки SQL такого вида означает, что база данных сильно разрослась. База данных обычно разрастается при большом количестве событий, которые записываются в таблицу PROTOCOL.
Решить данную проблему можно следующим образом:
- Частично очистить или удалить таблицу PROTOCOL:
- Если таблица PROTOCOL содержит важные события, которые нельзя удалять, а также при использовании подсистемы веб-отчетов, то БД событий следует вручную почистить от некоторых событий, для этого:
- Определить, какие события хранить в БД не требуется.
-
Удалить эти события SQL-запросами.
- После этого перейти к пункту 4, а после этого выполнить последовательно пункты 2 и 3.
-
Если таблица PROTOCOL не содержит важных событий, и подсистема веб-отчетов не используется, то для проблемного сервера принудительно вручную удалить таблицу PROTOCOL.
- Если таблица PROTOCOL содержит важные события, которые нельзя удалять, а также при использовании подсистемы веб-отчетов, то БД событий следует вручную почистить от некоторых событий, для этого:
-
Сжать базу данных.
-
Установить для базы данных минимальные параметры хранения log-файлов. Это можно сделать как на панели настройки раздела Интеллект в утилите tweaki.exe, так и с помощью ключей реестра.
-
Установить ограничение времени хранения событий в ПК Интеллект.
Также можно отключить протоколирование событий с помощью утилиты ddi.exe. Отключенные события можно удалить, что также поможет очистить базу данных. Для этого используются запросы SQL.