ALTER DATABASE failed because a lock could not be placed on database ‘DBNAME’. Try again later. in SQL Server

At times, we may need to take a database offline. And there is a chance that we encounter an error message like below.
How do we solve this issue and take the database offline?


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

Solution:
If there are any connections open, then there is a lock on the database while getting the database into Single user mode/taking offline.
To resolve the issue, as a first step you need to kill all the sessions on the database followed by the ALTER database statement.


USE master;

DECLARE @killSessions varchar(8000) = '';  
SELECT @killSessions = @killSessions + 'kill ' + CONVERT(varchar(5), spid) + ';'  
FROM master..sysprocesses  
WHERE dbid = db_id('dbname')
EXEC(@killSessions); 

ALTER DATABASE dbname SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO
ALTER DATABASE dbname SET OFFLINE WITH ROLLBACK IMMEDIATE
GO
ALTER DATABASE dbname  SET MULTI_USER;
Advertisements

The number of row value expressions in the INSERT statement exceeds the maximum allowed number of 1000 row values.

One of my colleague was facing an issue while inserting 2000 values to a table variable as below:


 DECLARE @EMPLOYEEDETAILS TABLE
(OLDEMPLOYEECODE NVARCHAR(30), NEWEMPLOYEECODE NVARCHAR(30))

INSERT INTO @EMPLOYEEDETAILS(OLDEMPLOYEECODE, NEWEMPLOYEECODE)
VALUES
('93466','0000007'),
('93467','0000010'),
...
...(2000 Records)
...
('93467','00002000')

Error Message:
Msg 10738, Level 15, State 1, Line 1006
The number of row value expressions in the INSERT statement exceeds the maximum allowed number of 1000 row values.

This is a self explanatory error message as SQL Server does not support row value expressions for more than 1000 values.
To overcome the issue, the code has been modified as below and the query has been executed successfully.

Solution:


DECLARE @EMPLOYEEDETAILS TABLE
(OLDEMPLOYEECODE NVARCHAR(30), NEWEMPLOYEECODE NVARCHAR(30))

INSERT INTO @EMPLOYEEDETAILS(OLDEMPLOYEECODE, NEWEMPLOYEECODE)
SELECT * FROM (VALUES
('93466','0000007'),
('93467','0000010'),
...
...(2000 Records)
...
('93467','00002000')
) A(Col1, Col2)

You may share any other alternatives/thoughts….