Saving changes is not permitted sql server ошибка

Из данного материала Вы узнаете, как устранить ошибку «Сохранение изменений запрещено», которая возникает в среде SQL Server Management Studio при работе с конструктором таблиц, а также мы поговорим о причинах ее возникновения

Всем привет! Сегодня я расскажу об ошибке «Сохранение изменений запрещено», которая возникает в среде SQL Server Management Studio при работе с конструктором таблиц, будут рассмотрены причины ее возникновения и, конечно же, способы исправления данной ошибки.

Ошибка «Сохранение изменений запрещено» в среде SSMS. Причины и способы устранения

Заметка! Обзор функционала SQL Server Management Studio (SSMS).

Содержание

  1. Ошибка «Сохранение изменений запрещено»
  2. Причины возникновения ошибки «Сохранение изменений запрещено»
  3. Способы устранения ошибки «Сохранение изменений запрещено»
  4. Использовать T-SQL
  5. Отключить параметр «Запретить сохранение изменений, требующих повторного создания таблицы»

Ошибка «Сохранение изменений запрещено»

Итак, ситуация: Вы вносите изменения в таблицу с помощью конструктора в среде SQL Server Management Studio, однако при попытке сохранить изменения Вы получаете следующую ошибку

Сохранение изменений запрещено. Чтобы сохранить изменения, необходимо удалить и повторно создать следующие таблицы. Либо изменения вносятся в таблицу, которую невозможно создать повторно, либо включен параметр «Запретить сохранение изменений, требующих повторного создания таблицы».

Скриншот 1

Причины возникновения ошибки «Сохранение изменений запрещено»

Дело в том, что при изменении таблицы с помощью конструктора с изменением структуры ее метаданных, чтобы сохранить все изменения, необходимо пересоздать таблицу на основе этих изменений, т.е. создать ее заново. Вы этого не видите, но это будет делать сама среда Management Studio.

Однако это действие может привести к потере метаданных и прямой потере данных во время повторного создания таблицы.

Поэтому по умолчанию в среде SQL Server Management Studio включен параметр «Запретить сохранение изменений, требующих повторного создания таблицы». И если Вы используете графический конструктор таблиц, чтобы внести изменения в таблицу, например, Вы выполняете следующие действия:

  • Меняете параметр «Разрешить значения NULL» для столбца;
  • Изменяете порядок столбцов в таблице;
  • Изменяете тип данных столбца;
  • Добавляете новый столбец.

то в этих случаях Вы будете получать именно такую ошибку.

Способы устранения ошибки «Сохранение изменений запрещено»

Вы можете спросить, «а как же тогда вносить изменения в таблицы, если существует прямой запрет на внесения изменений?».

Конечно же, существуют способы устранения данной ошибки и внесение изменений в таблицы. В частности, Вы можете использовать два.

Использовать T-SQL

Первый, и рекомендованный – это использовать инструкции T-SQL.

Заметка! Что такое T-SQL. Подробное описание для начинающих.

В качестве примера давайте представим, что у нас есть таблица Goods, и она имеет следующие данные.

   
   CREATE TABLE Goods(
	  ProductId INT IDENTITY(1,1) NOT NULL,
	  Category INT NOT NULL,
	  ProductName VARCHAR(100) NOT NULL,
	  Price MONEY NULL
   );

   INSERT INTO Goods (Category, ProductName, Price)
	    VALUES (1, 'Системный блок', 50),
		   (1, 'Клавиатура', 30),
		   (1, 'Монитор', 100),
		   (2, 'Планшет', 150),
		   (2, 'Смартфон', 100);

   SELECT * FROM Goods;

Скриншот 2

Заметка! Если Вас интересует язык SQL, то рекомендую почитать книгу «SQL код» – это самоучитель по языку SQL для начинающих программистов. В ней очень подробно рассмотрены основные конструкции языка.

Изменяем параметр «Разрешить значения NULL»

Как видим, столбец Price на текущий момент у нас может принимать значения NULL, однако мы решили сделать этот столбец обязательным к заполнению и запретить хранение в нем значений NULL.

Курс по SQL для начинающих

Если мы будем использовать конструктор таблиц, то мы получим ошибку «Сохранение изменений запрещено».

Чтобы запретить хранение NULL значений, мы можем выполнить следующую инструкцию SQL

   
   ALTER TABLE Goods ALTER COLUMN Price MONEY NOT NULL;

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

Изменяем тип данных столбца

Если необходимо изменить тип данных столбца, то нужно написать практически точно такую же инструкцию, только при этом указав новый тип данных.

   
   ALTER TABLE Goods ALTER COLUMN Price NUMERIC(18,2) NOT NULL;

В данном случае мы изменили тип данных столбца Price с MONEY на NUMERIC.

Добавляем новый столбец

Если требуется добавить новый столбец, то Вы можете использовать следующую инструкцию.

   
   ALTER TABLE Goods ADD ProductDescription VARCHAR(300) NULL;

В этом примере мы добавили столбец ProductDescription с типом данных VARCHAR.

К сожалению, изменение порядка столбцов в таблице на языке T-SQL не поддерживается, это возможно только путем пересоздания таблицы.

Заметка! Транзакции в T-SQL – основы для новичков с примерами.

Отключить параметр «Запретить сохранение изменений, требующих повторного создания таблицы»

Если Вы не хотите вникать в SQL, то Вы можете просто отключить параметр «Запретить сохранение изменений, требующих повторного создания таблицы» и в таком случае Вы сможете вносить в таблицы все перечисленные выше изменения, которые ранее были недоступны, включая изменение порядка столбцов.

Однако Microsoft не рекомендует отключать этот параметр, ссылаясь на то, что при определенных обстоятельствах сохранение изменений, требующих повторного создания таблицы, может привести к потере метаданных и прямой потере данных. Например, если у таблицы включен функционал «Отслеживания изменений».

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

Чтобы отключить данный параметр, зайдите в SSMS в меню «Сервис -> Параметры» и на вкладке «Конструкторы» снимите галочку «Запретить сохранение изменений, требующих повторного создания таблицы» и нажмите «ОК».

Скриншот 3

После этого Вы сможете сохранять любые изменения в таблицах с помощью графического конструктора.

Заметка! Курсы по Transact-SQL для начинающих.

На сегодня это все, надеюсь, материал был Вам полезен, пока!

In this article, we will discuss the reasons behind the “Saving changes is not permitted in SQL server” error. You will know how you can solve this error. Also, you will see some examples of this situation.

  • What are the reasons?
  • How can we fix it?
  • What is the alternative?
  • The best approach to solve the issue

What are the reasons?

Generally, this error arises when you try to alter the table structure like changing the data type. In SQL Server Management Studio, there are certain actions for which it drops the table and creates it again.

The possible actions can be:

  • You are trying to reorder the columns.
  • Trying to add a new column.
  • Changing the data type of a column.
  • Change the Allow Null settings for a column.
  • Change the table filegroup or its text/image data

Dropping the table can result in data loss. Therefore, the SQL Server Management Studio prevents this action and gives us a warning. There is an option “Prevent saving changes that require the table re-creation“ that is by default enabled and shows us this error.

saving changes is not permitted
Error

However, you can disable this option in the settings. We will see how we can disable this option in SQL Server Management Studio.

How can we fix it?

You can remove this error by disabling the the Prevent saving changes that require the table re-creation option in settings. The following steps will guide you to disable this option:

  • Go to Tools menu, click Options to open the options window.
saving changes is not permitted in sql server
Options Window
  • Click on Designers options and uncheck the option Prevent saving changes that require the table re-creation to disable the option and click OK.
saving changes is not permitted sql server
Disable the Prevent saving changes that require table re-creation Option
  • Once you have disabled this option, you will no longer face this issue.
  • However, it is not a good approach and you should try the alternative method.

Read: Identity Column in SQL Server

What is the alternative?

It is not necessary that you disable the Prevent saving changes that require the table re-creation option. You can also use the ALTER TABLE statement to perform some of the operations that generate this error.

For example, you want to change the data type of a column. If you will try it without query in SQL Server Management Studio, you will face the saving changes is not permitted error.

However, if you do this with the ALTER TABLE statement, you will not face this error. Note that the data type conversion of a column should be possible.

  • Consider the following structre of a table ProductsTable.
saving changes is not permitted in sql server 2019
ProductsTable Structure
  • Let us say you want to change the data type of the ProductID column from int to nchar(20). You will write the ALTER TABLE statement as:
ALTER TABLE dbo.ProductsTable
ALTER COLUMN ProductID nchar(20)
  • Now refresh the table and check its structure again.
saving changes is not permitted sql server 2019
Data Type Changed
  • Also, if the column had integer values earlier, the SQL Server will convert these values into nchar(20) values.

In this way, you can use the ALTER TABLE statement to perform other operations also like adding or removing the NULL property.

Read: Delete Duplicate Rows in SQL Server

The best approach to solve the issue

You should always use the ALTER TABLE statement to perform the operations like changing a column’s data type, adding or removing the NULL or NOT NULL constraints etc.

You can disable the Prevent saving changes that require the table re-creation option. However, it is not recommended to do so.

Disabling this option can result in data loss. This is because when you alter the table’s meta-structure, the SQL Server Management Studio will drop the table first and create it again.

Dropping of the table can result in the loss of various information. For example, in SQL Server, there is a feature named Change Tracking. If you have enabled this option, the SQL Server tracks changes to the table. If the table is dropped, this tracking information will also be deleted.

Thus, prefer to use the ALTER STATEMENT to change the meta-structure rather than using SQL Server Managemen Studio method and disabling the Prevent saving changes that require the table re-creation option.

Otherwise, disable this option only if you are not using the Change Tracking feature.

You may like the following sql server tutorials:

  • SQL Server Convert Function
  • SQL Server Convert Datetime to date
  • Exception Handling in SQL Server
  • SQL Server convert integer to string
  • SQL Server Create Temp Table

In this sql server tutorial, we learned how to fix errors, Saving changes is not permitted in SQL Server. The reason for the error and fixes for Saving changes is not permitted in SQL Server.

Bijay

I am Bijay having more than 15 years of experience in the Software Industry. During this time, I have worked on MariaDB and used it in a lot of projects. Most of our readers are from the United States, Canada, United Kingdom, Australia, New Zealand, etc.

Want to learn MariaDB? Check out all the articles and tutorials that I wrote on MariaDB. Also, I am a Microsoft MVP.

Problem

Some Confluence troubleshooting steps require you to make changes to a SQL Server database. Depending on your SQL Server configuration, you may get the following error when making structure/schema changes: 

Saving changes is not permitted. The changes that you have made require the following tables to be dropped and re-created. You have either made changes to a table that can't be re-created or enabled the option Prevent saving changes that require the table to be re-created.

Cause

This warning that prevents the actions from completing is caused by the Prevent saving changes that require table re-creation option being triggered in SQL Server. This option lets SQL Server to prevent structure changes when a table needs to be recreated and is intended as a security feature. However, this also prevents planned changes from completing. 

Resolution

The resolution is to uncheck the Prevent saving changes that require table re-creation option:

As with all recommendations made by Atlassian Support, please follow best practices for Change Management and test and validate these settings in a Test/Development and Staging environment prior to rolling any changes into a Production environment. This is to validate these changes and ensure that they will function will within your infrastructure prior to placing these changes in production.

  1. Open SQL Management Studio as an administrator
  2. Go to Tools, then options then «Designer»
  3. Uncheck the Prevent saving changes that require table re-creation
  4. Expand the database tables on the left object explorer of SQL Server and make the changes you plan to make
  5. You may want to re-check the Prevent saving changes that require table re-creation in order to for the security feature to warn again

Last modified on Mar 30, 2016

Related content

  • No related content found

You might have faced an error as shown below, when you make some changes in table from design mode in SQL server management studio (SSMS).

‘Saving changes is not permitted. The change you have made requires the following table to be dropped and re-created. You have either made changes to a table that can’t be recreated or enabled the option prevent saving changes that require the table to be re-created.’

It usually happens when you make any change that require the table to be dropped and re-created such as changing the column data type, Adding a column between two existing columns, changing the column nullability, or deleting a column from design mode in SSMS.

Lets see the case when an error occurs, and try to resolve that.

Suppose you have a EmployeeData table and you need to change the column data type size for EmpName column.

Lets do this using design mode in SQL server management studio (SSMS).

To open the table in design mode, just right click on table, and click on Design.

Once you click on Design, you will see a table is opened in edited mode as shown below.

Lets change the data type size of column EmpName from varchar(50) to varchar(100).

After making changes in data type size, when you try save the change by pressing Ctrl +S.

You  will get an error message as shown below.

Click on Cancel button to close error message dialog box.

You can resolve this error by changing the default table setting for editing a table from design mode.

Lets go step by step and change the setting for editing a table.

In SQL Server Management Studio (SSMS), Go to Tools then click on Option..

After that a Options dialog box opens,  now expand the Designers, and select Tables and Database Designers. 

Now on the right side, you will see a table options there uncheck the box Prevent saving changes that require table re-creation.

Also Note that: By unchecking this option, when you change a table basically you alter the metadata structure of the table, and then save the table, the table must be re-created based on these changes. This may result in the loss of metadata and in a direct loss of data during the re-creation of the table. So it is recommended that to use T-SQL alter table command for modifying a table definition such as altering, adding, or dropping columns and constraints.  

After that click OK to save the settings.

After making changes in setting, Lets try to change the data type size again.

You can see, this time it does not return any error and changes in table are saved.

Also Read..

Get Dark theme in SQL Server Management studio

Get the detailed information of all datatypes in SQL Server

SQL Basics Tutorial SQL Advance Tutorial SSRS Interview Q & A
SQL Create table SQL Server Stored Procedure Create a New SSRS Project List Of SQL Server basics to Advance Level Interview Q & A
SQL ALTER TABLE SQL Server Merge Create a Shared Data Source in SSRS SQL Server Question & Answer Quiz
SQL Drop SQL Server Pivot Create a SSRS Tabular Report / Detail Report
….. More …. More ….More
Power BI Tutorial Azure Tutorial Python Tutorial SQL Server Tips & Tricks
Download and Install Power BI Desktop Create an Azure storage account Learn Python & ML Step by step Enable Dark theme in SQL Server Management studio
Connect Power BI to SQL Server Upload files to Azure storage container SQL Server Template Explorer
Create Report ToolTip Pages in Power BI Create Azure SQL Database Server Displaying line numbers in Query Editor Window
….More ….More ….More

 3,716 total views,  1 views today

I was thinking in calling these post series “Note to myself”, only not to be always looking for these solutions whenever these problems not related to BizTalk Server or other integration products or technologies occur. But I decided to call it “A fish out of water” that basically is what I feel sometimes. And to start this post series I choose an occurrent “issue” that happens a lot when I’m trying to do something whit in SQL Server Management Console: Saving changes is not permitted.

The full warning message would be:

Saving changes is not permitted. The changes that you have made require the following tables to be dropped and re-created. You have either made changes to a table that can’t be re-created or enabled the option Prevent saving changes that require the table to be re-created.

SQL Server Management Console: Saving changes is not permitted

This behavior is very simple to solve and is well documented here: Error message when you try to save a table in SQL Server: “Saving changes is not permitted”. Once again, this is just for helping me not always to look at this “problem” again. My Blog is the first place I look, it is my personal notes.

Cause

This problem occurs when the Prevent saving changes that require the table re-creation option is enabled, and you make one or more of the following changes to the table:

  • You change the Allow Nulls setting for a column.
  • You reorder columns in the table.
  • You change the column data type.
  • You add a new column.

When you change a table so that you alter the metadata structure of the table, and then you save the table, the table must be re-created based on these changes. This may result in the loss of metadata and in a direct loss of data during the re-creation of the table. If you enable the Prevent saving changes that require the table re-creation option in the Designer section of the SQL Server Management Studio (SSMS) Options window, you receive the error message: Saving changes is not permitted. The changes that you have made require the following tables to be dropped and re-created.

Solution

To change the Prevent saving changes that require the table re-creation option, follow these steps:

  • Open SQL Server Management Studio (SSMS).
  • On the Tools menu, click Options.
  • In the navigation pane of the Options window, click Designers.
  • Uncheck (clear) the Prevent saving changes that require the table re-creation checkbox, and then click OK.
SQL Server Management Console: Saving changes is not permitted fixed

#1 Azure Monitoring Platform

Sandro Pereira lives in Portugal and works as a consultant at DevScope. In the past years, he has been working on implementing Integration scenarios both on-premises and cloud for various clients, each with different scenarios from a technical point of view, size, and criticality, using Microsoft Azure, Microsoft BizTalk Server and different technologies like AS2, EDI, RosettaNet, SAP, TIBCO etc.

He is a regular blogger, international speaker, and technical reviewer of several BizTalk books all focused on Integration. He is also the author of the book “BizTalk Mapping Patterns & Best Practices”. He has been awarded MVP since 2011 for his contributions to the integration community.
View all posts by Sandro Pereira

Понравилась статья? Поделить с друзьями:
  • Sapphire rx 470 4gb nitro ошибка 43
  • Sapphire plugins error
  • Sapphire plugin error
  • Sap как изменить тип сообщения
  • Sap validation error