Не удалось выполнить инструкцию alter database

Проблемы

Предположим, что вы подключаетесь к базе данных Microsoft Azure SQL версии 12 с помощью Microsoft SQL Server Management Studio 2014. При включении параметра отслеживания изменений для базы данных SQL Azure с помощью диалогового окна » Свойства базы данных » может появиться сообщение об ошибке. Например, если изменить значение параметра Отслеживание изменений на true в диалоговом окне Свойства базы данных Azure SQL, а затем нажать кнопку ОК, может появиться сообщение об ошибке, подобное следующему:

Не удалось выполнить инструкцию ALTER DATABASE «имя базыданных». (Microsoft. SqlServer. SMO) Дополнительные сведения: возникло исключение при выполнении инструкции или пакета Transact-SQL. (Microsoft. SqlServer. ConnectionInfo) В базе данных «Master» нет разрешения на просмотр состояния базы данных. У пользователя нет разрешения на выполнение этого действия. (Microsoft SQL Server, ошибка: 262)

Решение

Эта проблема впервые устранена в следующем накопительном обновлении SQL Server:

Накопительное обновление 1 для SQL Server 2014 с пакетом обновления 1 (SP1)

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

Версии сборки SQL Server 2014

Статус

Корпорация Майкрософт подтверждает наличие этой проблемы в своих продуктах, которые перечислены в разделе «Применяется к».

Ссылки

Ознакомьтесь с терминологией , которую корпорация Майкрософт использует для описания обновлений программного обеспечения.

Нужна дополнительная помощь?

Нужны дополнительные параметры?

Изучите преимущества подписки, просмотрите учебные курсы, узнайте, как защитить свое устройство и т. д.

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

  • Remove From My Forums

 none

Изменение параметров сортировки базы данных

  • Вопрос

  • В настройках сервера сортировка указана — Cyrillic_General_CI_AS

    Моя пользовательская база установилась с сортировкой — SQL_Latin1_General_CP1_CI_AS

    Пробовал изменить сортировку с помощью ALTER DATABASE database_name COLLATE Cyrillic_General_CI_AS, в ответ получал вот такие ошибки:
    Сообщение 5030, уровень 16, состояние 2, строка 1
    Базу данных нельзя заблокировать монопольно для выполнения операции.
    Сообщение 5072, уровень 16, состояние 1, строка 1
    Не удалось выполнить инструкцию ALTER DATABASE. Параметрам сортировки по умолчанию для базы данных «OperationsManager» невозможно установить значение Cyrillic_General_CI_AS

    Есть какой-нибудь более-менее простой способ изменить сортировку без пересоздания все баз данных?

    Благодарю всех за помощь!

Ответы

  • Выполните до:
    alter database database_name set single_user with rollback immediate

    Выполните после:
    alter database database_name set multi_user

    • Помечено в качестве ответа

      26 апреля 2010 г. 9:42

I need to restart a database because some processes are not working. My plan is to take it offline and back online again.

I am trying to do this in Sql Server Management Studio 2008:

use master;
go
alter database qcvalues
set single_user
with rollback immediate;
alter database qcvalues
set multi_user;
go

I am getting these errors:

Msg 5061, Level 16, State 1, Line 1
ALTER DATABASE failed because a lock could not be placed on database 'qcvalues'. Try again later.
Msg 5069, Level 16, State 1, Line 1
ALTER DATABASE statement failed.
Msg 5061, Level 16, State 1, Line 4
ALTER DATABASE failed because a lock could not be placed on database 'qcvalues'. Try again later.
Msg 5069, Level 16, State 1, Line 4
ALTER DATABASE statement failed.

What am I doing wrong?

nalply's user avatar

nalply

26.3k15 gold badges78 silver badges100 bronze badges

asked Jan 12, 2011 at 19:23

JOE SKEET's user avatar

4

After you get the error, run

EXEC sp_who2

Look for the database in the list. It’s possible that a connection was not terminated. If you find any connections to the database, run

KILL <SPID>

where <SPID> is the SPID for the sessions that are connected to the database.

Try your script after all connections to the database are removed.

Unfortunately, I don’t have a reason why you’re seeing the problem, but here is a link that shows that the problem has occurred elsewhere.

http://www.geakeit.co.uk/2010/12/11/sql-take-offline-fails-alter-database-failed-because-a-lock-could-not-error-5061/

answered Jan 12, 2011 at 19:50

bobs's user avatar

bobsbobs

21.7k12 gold badges66 silver badges78 bronze badges

5

I managed to reproduce this error by doing the following.

Connection 1 (leave running for a couple of minutes)

CREATE DATABASE TESTING123
GO

USE TESTING123;

SELECT NEWID() AS X INTO FOO
FROM sys.objects s1,sys.objects s2,sys.objects s3,sys.objects s4 ,sys.objects s5 ,sys.objects s6

Connections 2 and 3

set lock_timeout 5;

ALTER DATABASE TESTING123 SET SINGLE_USER WITH ROLLBACK IMMEDIATE;

answered Jan 12, 2011 at 20:11

Martin Smith's user avatar

Martin SmithMartin Smith

434k87 gold badges737 silver badges836 bronze badges

Just to add my two cents. I’ve put myself into the same situation, while searching the minimum required privileges of a db login to run successfully the statement:

ALTER DATABASE ... SET SINGLE_USER WITH ROLLBACK IMMEDIATE

It seems that the ALTER statement completes successfully, when executed with a sysadmin login, but it requires the connections cleanup part, when executed under a login which has «only» limited permissions like:

ALTER ANY DATABASE

P.S. I’ve spent hours trying to figure out why the «ALTER DATABASE..» does not work when executed under a login that has dbcreator role + ALTER ANY DATABASE privileges. Here’s my MSDN thread!

answered Jul 20, 2015 at 17:00

Veselin Z.'s user avatar

I will add this here in case someone will be as lucky as me.

When reviewing the sp_who2 list of processes note the processes that run not only for the effected database but also for master. In my case the issue that was blocking the database was related to a stored procedure that started a xp_cmdshell.

Check if you have any processes in KILL/RollBack state for master database

SELECT *
FROM sys.sysprocesses
WHERE cmd = 'KILLED/ROLLBACK'

If you have the same issue, just the KILL command will probably not help.
You can restarted the SQL server, or better way is to find the cmd.exe under windows processes on SQL server OS and kill it.

answered Jan 8, 2018 at 14:10

Alina's user avatar

AlinaAlina

314 bronze badges

In SQL Management Studio, go to Security -> Logins and double click your Login. Choose Server Roles from the left column, and verify that sysadmin is checked.

In my case, I was logged in on an account without that privilege.

HTH!

answered Dec 28, 2012 at 15:25

Marty's user avatar

MartyMarty

9236 silver badges6 bronze badges

1

Killing the process ID worked nicely for me.
When running «EXEC sp_who2» Command over a new query window… and filter the results for the «busy» database , Killing the processes with «KILL » command managed to do the trick. After that all worked again.

aaaidan's user avatar

aaaidan

6,9938 gold badges65 silver badges102 bronze badges

answered Jun 27, 2014 at 22:43

user3749524's user avatar

0

I know this is an old post but I recently ran into a very similar problem. Unfortunately I wasn’t able to use any of the alter database commands because an exclusive lock couldn’t be placed. But I was never able to find an open connection to the db. I eventually had to forcefully delete the health state of the database to force it into a restoring state instead of in recovery.

answered Feb 9, 2017 at 19:04

Geoff Dawdy's user avatar

Geoff DawdyGeoff Dawdy

8676 gold badges15 silver badges41 bronze badges

In rare cases (e.g., after a heavy transaction is commited) a running CHECKPOINT system process holding a FILE lock on the database file prevents transition to MULTI_USER mode.

answered Aug 14, 2018 at 12:52

mitix's user avatar

mitixmitix

1851 silver badge8 bronze badges

In my scenario, there was no process blocking the database under sp_who2. However, we discovered because the database is much larger than our other databases that pending processes were still running which is why the database under the availability group still displayed as red/offline after we tried to ‘resume data’by right clicking the paused database.

To check if you still have processes running just execute this command:
select percent complete from sys.dm_exec_requests
where percent_complete > 0

answered May 31, 2019 at 14:12

user123456789's user avatar

  • Remove From My Forums
  • Question

  • At the end of the month we have a sql agent job for each database. The first thing it does is take the database off line and then immediately back online. These jobs have been working for years. Now at one client’s sql server, maybe 25 of his 45 databases
    failed with «5069 ALTER DATABASE statement failed» when running the statement «ALTER DATABASE [DataBaseName] SET ONLINE». This morning when we reran the failed SQL Agent Jobs, they all ran without error. 

    Any ideas on why so many databases would fail on the SET ONLINE? 

RRS feed

  • Remove From My Forums
  • Question

  • Hi!

    I’m runing sql script on sql server express 2008 sp2 end i’m getting this error. 

    «ALter database statement failed line 20, 5069»

    in the line 20 i have the «GO» statement

    I’ve tried to kill all connections to this database but no result.

    plz help me

Answers

  • it works, the problem was the in the authentification mode, when i use SA account it works nicely.

    thx

    • Marked as answer by
      Nissanna
      Wednesday, January 13, 2016 10:28 AM

All replies

  • Nissanna,

    This error occurs because a lock could not be placed in database.

    Try to use the statement below to disconnect all users from the database before:

    ALTER DATABASE [DBName] SET SINGLE_USER WITH ROLLBACK IMMEDIATTE


    Felipe Lauffer MCSA: SQL Server | MCP

  • Can you show us the query ?

    What are you trying to do with alter database command ?

    From where are you running this command , from SSMS or from something else


    Please mark this reply as answer if it solved your issue or vote as helpful if it helped so that other forum members can benefit from it

    My Wiki Articles

    MVP

  • Nissanna,

    This error occurs because a lock could not be placed in database.

    Try to use the statement below to disconnect all users from the database before:

    ALTER DATABASE [DBName] SET SINGLE_USER WITH ROLLBACK IMMEDIATTE

    What are you suggesting would you do the same on your production database which is running . Let us first see what OP’s problem is Alter database can be used to do lot of things .

    The above command could be very dangerous if applied out of context


    Please mark this reply as answer if it solved your issue or vote as helpful if it helped so that other forum members can benefit from it

    My Wiki Articles

    MVP

  • Same problem, i get the same error in this statement 

  • I’m running this script: 

    USE [master]
    GO    
    declare @Path nvarchar(512)
    SELECT @Path=SUBSTRING(physical_name, 1, CHARINDEX(N’master.mdf’, LOWER(physical_name)) — 1) 
           FROM master.sys.master_files
           WHERE database_id = 1 AND file_id = 1

     
    declare @dbname varchar(100)
    set @dbname = ‘dbname’

    DECLARE @Query VARCHAR(MAX)=»
    SET @Query = @Query + ‘CREATE DATABASE ‘+@dbName +’ ON  PRIMARY ‘
    SET @Query = @Query + ‘( NAME = »’+@dbName +»’, FILENAME = N»’+@path+@dbName +’.mdf» , SIZE = 6144KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB ) ‘
    SET @Query = @Query + ‘ LOG ON ‘
    SET @Query = @Query + ‘( NAME = »’+@dbName +’_log», FILENAME = N»’+@path+@dbName +’_log.ldf» , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)’

     
    exec (@Query)

    ALTER DATABASE [dbname] SET COMPATIBILITY_LEVEL = 100
    GO  —>here the pb appears
    IF (1 = FULLTEXTSERVICEPROPERTY(‘IsFullTextInstalled’))
    begin
    EXEC [dbname].[dbo].[sp_fulltext_database] @action = ‘enable’
    end
    GO
    ALTER DATABASE [dbname] SET ANSI_NULL_DEFAULT OFF 
    GO
    ALTER DATABASE [dbname] SET ANSI_NULLS OFF 
    GO
    ALTER DATABASE [dbname] SET ANSI_PADDING OFF 
    GO
    ALTER DATABASE [dbname] SET ANSI_WARNINGS OFF 
    GO
    ALTER DATABASE [dbname] SET ARITHABORT OFF 
    GO
    ALTER DATABASE [dbname] SET AUTO_CLOSE OFF 
    GO
    ALTER DATABASE [dbname] SET AUTO_CREATE_STATISTICS ON 
    GO
    ALTER DATABASE [dbname] SET AUTO_SHRINK OFF 
    GO
    ALTER DATABASE [dbname] SET AUTO_UPDATE_STATISTICS ON 
    GO
    ALTER DATABASE [dbname] SET CURSOR_CLOSE_ON_COMMIT OFF 
    GO
    ALTER DATABASE [dbname] SET CURSOR_DEFAULT  GLOBAL 
    GO
    ALTER DATABASE [dbname] SET CONCAT_NULL_YIELDS_NULL OFF 
    GO
    ALTER DATABASE [dbname] SET NUMERIC_ROUNDABORT OFF 
    GO
    ALTER DATABASE [dbname] SET QUOTED_IDENTIFIER OFF 
    GO
    ALTER DATABASE [dbname] SET RECURSIVE_TRIGGERS OFF 
    GO
    ALTER DATABASE [dbname] SET  DISABLE_BROKER 
    GO
    ALTER DATABASE [dbname] SET AUTO_UPDATE_STATISTICS_ASYNC OFF 
    GO
    ALTER DATABASE [dbname] SET DATE_CORRELATION_OPTIMIZATION OFF 
    GO
    ALTER DATABASE [dbname] SET TRUSTWORTHY OFF 
    GO
    ALTER DATABASE [dbname] SET ALLOW_SNAPSHOT_ISOLATION OFF 
    GO
    ALTER DATABASE [dbname] SET PARAMETERIZATION SIMPLE 
    GO

  • The script doesn’t contain errors.

    Are you sure you have SqlServer 2008 or higher?

    Maybe you’re running your script on SqlServer 2005.

    Hope this help


    Please mark this reply as answer if it solved your issue or vote as helpful if it helped so that other forum members can benefit from it

  • now i’m using sql server express 2008 sp1, i think it’s a problem of user permission 

  • Of course requires ALTER permission on the database.

    Do you have it?


    Please mark this reply as answer if it solved your issue or vote as helpful if it helped so that other forum members can benefit from it

  • i know, of course, but i’m still getting the pb 

  • i know, of course, but i’m still getting the pb 

    Can you just run below part of query and see if database is created

    USE [master]
     GO    
     declare @Path nvarchar(512)
     SELECT @Path=SUBSTRING(physical_name, 1, CHARINDEX(N'master.mdf', LOWER(physical_name)) - 1) 
            FROM master.sys.master_files
            WHERE database_id = 1 AND file_id = 1
      
     declare @dbname varchar(100)
     set @dbname = 'dbname'
     
    DECLARE @Query VARCHAR(MAX)=''
     SET @Query = @Query + 'CREATE DATABASE '+@dbName +' ON  PRIMARY '
     SET @Query = @Query + '( NAME = '''+@dbName +''', FILENAME = N'''+@path+@dbName +'.mdf'' , SIZE = 6144KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB ) '
     SET @Query = @Query + ' LOG ON '
     SET @Query = @Query + '( NAME = '''+@dbName +'_log'', FILENAME = N'''+@path+@dbName +'_log.ldf'' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)'
      
     exec (@Query)
     

    After this select new query in database and then run rest of the script


    Please mark this reply as answer if it solved your issue or vote as helpful if it helped so that other forum members can benefit from it

    My Wiki Articles

    MVP

    • Proposed as answer by
      Ice Fan
      Wednesday, January 13, 2016 10:19 AM

  • But the database
    is successfully created?


    Please mark this reply as answer if it solved your issue or vote as helpful if it helped so that other forum members can benefit from it

  • YEs, the database is successfully created with this part 

    USE [master]
     GO    
     declare @Path nvarchar(512)
     SELECT @Path=SUBSTRING(physical_name, 1, CHARINDEX(N'master.mdf', LOWER(physical_name)) - 1) 
            FROM master.sys.master_files
            WHERE database_id = 1 AND file_id = 1
      
     declare @dbname varchar(100)
     set @dbname = 'dbname'
     
    DECLARE @Query VARCHAR(MAX)=''
     SET @Query = @Query + 'CREATE DATABASE '+@dbName +' ON  PRIMARY '
     SET @Query = @Query + '( NAME = '''+@dbName +''', FILENAME = N'''+@path+@dbName +'.mdf'' , SIZE = 6144KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB ) '
     SET @Query = @Query + ' LOG ON '
     SET @Query = @Query + '( NAME = '''+@dbName +'_log'', FILENAME = N'''+@path+@dbName +'_log.ldf'' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)'
      
     exec (@Query)
     
  • i don’t why, but it works for me with cmd line. i didn’t add any thing.

    thx 

  • Did you tried my approach and did it worked ?


    Please mark this reply as answer if it solved your issue or vote as helpful if it helped so that other forum members can benefit from it

    My Wiki Articles

    MVP

  • in fact, i’m using this script in installshield 2010, it doesn’t create the database, thought when i run just the script on the cmd line or in SSMS it works nicely, i think that installshield doesn’t execute the EXEC statement. 

  • You can put your code in a file (sqlscript.sql) and after that
    Try this with the command prompt (CMD.EXE):
    osql.exe /U username /P password /S server /d database /i sqlscript.sql /o sqlscript.output


    Please mark this reply as answer if it solved your issue or vote as helpful if it helped so that other forum members can benefit from it

  • it works, the problem was the in the authentification mode, when i use SA account it works nicely.

    thx

    • Marked as answer by
      Nissanna
      Wednesday, January 13, 2016 10:28 AM

  • Hi Nissanna,

    Glad to hear that the issue is resolved. Thanks for your sharing, other community members could benefit from your solution.

    Thanks,
    Ice fan


    Ice Fan
    TechNet Community Support

Понравилась статья? Поделить с друзьями:
  • Экстермин от тараканов инструкция по применению
  • Пеногаситель пищевой для браги инструкция по применению
  • Пимафуцин крем для мужчин инструкция по применению для чего применяется
  • Параллельная парковка на автодроме пошаговая инструкция автомат видео
  • Стугерон инструкция по применению цена отзывы аналоги кому прописывают