Database is in Transition state - sql-server

Today I was trying to restore a database over an already existing database, I simply right clicked the database in SSMS --> Tasks --> Take Offline so I could restore the database.
A small pop up window appeared and showed Query Executing..... for sometime and then threw an error saying Database is in use cannot take it offline. From which I gathered there are some active connections to that database so I tried to execute the following query
USE master
GO
ALTER DATABASE My_DatabaseName
SET OFFLINE WITH ROLLBACK IMMEDIATE
GO
Again at this point the SSMS showed Query Executing..... for a sometime and then threw the following error:
Msg 5061, Level 16, State 1, Line 1
ALTER DATABASE failed because a lock could not be placed on database 'My_DatabaseName'. Try again later.
Msg 5069, Level 16, State 1, Line 1
ALTER DATABASE statement failed.
After this I could not connect to the database through SSMS. and when I tried to Take it offline using SSMS it threw an error saying:
Database is in Transition. Try later .....
At this point I simply could'nt touch the database anything I tried it returned the same error message Database is in Transition.
I got on google read some questions where people had faced similar issue and they recommended to close the SSMS and open it again, So did I and
Since it was only a dev server I just deleted the database using SSMS and restored on a new database.
My question is what could have possibly caused this ?? and how I can Avoid this to happen in future and if I ever end up in the same situation in future is there any other way of fixing it other then deleting the whole database ???
Thank you

Check this out. This will help you release locks. Works great! https://dba.stackexchange.com/questions/57432/database-is-in-transition-error
use this
select
l.resource_type,
l.request_mode,
l.request_status,
l.request_session_id,
r.command,
r.status,
r.blocking_session_id,
r.wait_type,
r.wait_time,
r.wait_resource,
request_sql_text = st.text,
s.program_name,
most_recent_sql_text = stc.text
from sys.dm_tran_locks l
left join sys.dm_exec_requests r
on l.request_session_id = r.session_id
left join sys.dm_exec_sessions s
on l.request_session_id = s.session_id
left join sys.dm_exec_connections c
on s.session_id = c.session_id
outer apply sys.dm_exec_sql_text(r.sql_handle) st
outer apply sys.dm_exec_sql_text(c.most_recent_sql_handle) stc
where l.resource_database_id = db_id('<YourDatabase>')
order by request_session_id;
and then
for each processnumber
kill <processnumber>

Check out this article.
http://oostdam.info/index.php/sectie-blog/289-sql-error-952-8ways-to-solve-it
I use TSQL most of the time, so I have not run into this issue yet.
What version is the SQL Server database and at what patch level?
Next time, do a usp_who2 to see what threads are running.
http://craftydba.com/wp-content/uploads/2011/09/usp-who2.txt
Since the output is in a table, you can search by database.
Kill all threads using the database before the trying the ALTER statement.
A night about 6 months ago, I had a terrible time getting a 2000 database offline due to an application constantly hitting it. I eventually disabled the user account so I would not get any more logins.

Related

SSIS package with CHANGE TRACKING keeps missing records

I have an SSIS package using CHANGE TRACKING that runs every 5 minutes to perform one way synchronization on a table.
These are the DB's involved:
DestDB
SourceDB
DestDB contains a table called TableSyncVersions that is used to keep track of the most recent Sync version used to extract information from the table in SourceDB. This Sync Version is used for the next execution of the package to get the next batch of data.
SourceDB has Snapshot Isolation enabled and the CT Query is being executed by an "OLE DB Source" in SSIS. The Query is as follows:
SET TRANSACTION ISOLATION LEVEL SNAPSHOT;
BEGIN TRAN;
--Using OLE DB parameters to capture the current version within the transaction
SELECT ? = CAST(CHANGE_TRACKING_CURRENT_VERSION() AS NVARCHAR)
SELECT ct.KeyColumn1
, ct.KeyColumn2
, ct.KeyColumn3
, st.Column1
, st.Column2
, st.Column3
, st.Column4
, ct.SYS_CHANGE_OPERATION
FROM TABLE1 AS st
--Using OLE DB Parameters to reference the version # saved in TableSyncVersions
RIGHT OUTER JOIN CHANGETABLE(CHANGES TABLE1, ?) AS ct
ON avq.KeyColumn1 = ct.KeyColumn1
AND avq.KeyColumn2 = ct.KeyColumn2
AND avq.KeyColumn3 = ct.KeyColumn3
COMMIT TRAN;
Here is a screen shot of the Control Flow for this package:
At least once a day, the package misses 5-20 records even though it ran without error, the records are missed at different times everyday. Has anyone experienced anything like this with Change Tracking before?
Any help is greatly appreciated.
Thank you,
Tory Hill

removing an object from Publication database sys.sp_droparticle and sp_dropsubscription

SQL Server Admin is not my forte. So please bear with while I explain this
A SQL Server 2012 cluster is involved in a Change data capture ( CDC ) effort using a 3rd party CDC utility. for it to work replication needs to be turned on, without replication CDC will not work. The CDC taps some 2000+ odd tables from SQL Server in a database Db1. Out of these we found out that some 200+ tables undergo truncate and load as against increments. So we removed those from our CDC lists but since replication is turned on at DB Level we also need to remove these from publication database so that truncates happening to this exception list wont need replication switched off DB level ( aka truncates to these tables and replication can co-exist. As its known, for truncates to happen we need to switch off replication. The code is in prod so replacing truncate by delete is not an option now besides the fact that for billion row tables deletes are going to be expensive & time consuming )
The above is the requirement. So based on that if a better solution can be conceived do let me know
What I tried :
EXEC sys.sp_droparticle #publication = 'pub', #article = 'art', #force_invalidate_snapshot = 1
Error I get
Msg 14013, Level 16, State 1, Procedure sp_MSrepl_droparticle, Line 104 [Batch Start Line 2]
This database is not enabled for publication.
Another SP
DECLARE #subscriber AS sysname;
EXEC sp_dropsubscription #publication = 'AR_PUBLICATION_00010', #article = 'BPA_BRGR_RUL_GRP_R' ,#subscriber=#subscriber
Msg 14013, Level 16, State 1, Procedure sp_MSrepl_dropsubscription, Line 55 [Batch Start Line 1]
This database is not enabled for publication.
But using GUI I am able to uncheck the tables I dont want in that publication. ( right click publication --> properties --> articles --> check /uncheck whatever you want excluded ) . I dont have any subscription just there is a publication.
Whatever code I ran through GUI above I can def. run through T-SQL But I dont know what code was it that was run ? How do I get this done using a scripting approach. I have 200+ tables to deal with and unchecking em 1 by 1 ain't helping
Nearly four years late, but in case it helps anyone... I think you want sp_dropmergearticle not sp_droparticle.
EXEC sys.sp_dropmergearticle #publication = 'pub', #article = 'art', #force_invalidate_snapshot = 1
I was getting an identical error message using sp_droparticle, but sp_dropmergearticle removed the table from the publication and allowed me to delete it.
Whatever code I ran through GUI above I can def. run through T-SQL But I dont know what code was it that was run ? How do I get this done using a scripting approach.
SSMS does not have a special API. Everything it does, it does through TSQL. So use SQL Profiler to watch what SSMS does, and capture the script.

Detect the cause of SQL Server update lock

Problem:
A .NET application during business transaction executes a query like
UPDATE Order
SET Description = 'some new description`
WHERE OrderId = #p1 AND RowVersion = #p2
This query hangs until timeout (several minutes) and then I get an exception:
SqlException: Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
It is reproduced, when database is under heavy load (several times per day).
I need to detect the cause of the lock of the query.
What I've tried:
Exploring activity monitor - it shows that the query is hanging by lock. Filtering by headblocker does not give much, it is frequently changing.
Analyze SQL script, that gives similar to activity monitor data - almost same result as looking to activity monitor. Chasing blocking_session_id results in some session, that awaits for command or executing some SQL, I can't reason a relation to Order table. Executing the same script in a second gives other session. I also tried a some other queries/stored procedures from this atritcle with no result.
Building standard SQL Server report for locked/problem transactions results in errors like Max recursion exhausted or Local OutOfMemory Exception (I have 16 Gb RAM).
Database Details
Version: SQL Server 2016
Approximate number of concurrent queries per second by apps to database: 400
Database size: 1.5 Tb
Transaction isolation level: ReadUncommited for readonly transactions, Serializable for transactions with modifications
I'm absolutely new to this kind of problems, so I have missed a lot for sure.
Any help or direction would be great!
In case anyone interested, I have found this particular query espesially usefull:
SELECT tl.resource_type
,OBJECT_NAME(p.object_id) AS object_name
,tl.request_status
,tl.request_mode
,tl.request_session_id
,tl.resource_description
,(select text from sys.dm_exec_sql_text(r.sql_handle))
FROM sys.dm_tran_locks tl
INNER JOIN sys.dm_exec_requests r ON tl.request_session_id=r.session_id
LEFT JOIN sys.partitions p ON p.hobt_id = tl.resource_associated_entity_id
WHERE tl.resource_database_id = DB_ID()
AND OBJECT_NAME(p.object_id) = '<YourTableName>'
ORDER BY tl.request_session_id
It shows transactions, that have acquired locks on <YourTableName> and what query they are executing now.
Try to use sys.dm_exec_requests view, and filter by columns blocking_session_id, wait_time

SQL Server 2012 - Finding out which transaction logs have been applied to a NORECOVER db

I have a copy of an offsite production database used for reporting which is running on SQL Server 2012. I want to start updating it hourly with transaction logs from that offsite production database.
No big deal, restore a full backup (w/ NORECOVERY) to get things started and apply the transaction logs (w/ NORECOVERY) as they come in.
However, in the event of a problem with the restore (or with getting the log files) I could end up with several transaction log files, some of which have been applied and others that have not. When that happens, how do I figure out which file to start with in my TSQL script?
I tried looking in the restore history table like this:
select distinct
h.destination_database_name,
h.restore_date,
s.server_name,
m.physical_device_name as backup_device,
f.physical_name
from
msdb..restorehistory h
inner join
msdb..backupfile f on h.backup_set_id = f.backup_set_id
inner join
msdb..backupset s on f.backup_set_id = s.backup_set_id
inner join
msdb..backupmediafamily m on s.media_set_id = m.media_set_id
where
h.destination_database_name = 'mydb'
and h.restore_date > (GETDATE() -0.5)
order by
h.restore_date
But checking restorehistory is no good because the NORECOVERY flag means no records have been added in that table. So is there another way to check this, via T-SQL, that works for a NORECOVERY database?
Assuming this is a rare manual operation, the simplest way to is scan the errorlog.
SQL Server's built-in log shipping (and some third party implementations) have tables, views and user interfaces that make this simpler.

Local SQL Server: The specified procedure could not be found

This problem has appeared on my PC a few days ago, without any changes I have made to the Visual Studio/SQL Server settings.
When trying to perform any manual operation on the database file (*.mdf) in Visual Studio, I get the following error:
The specified procedure could not be found. (Exception from HRESULT: 0x8007007F)
(For example, when trying to create a new table, or when showing an existing table's data)
How I can fix this error?
Be sure you or someone else has not changed your rights on master. In order to add anything a record is added to that table.
Addendum:
You can run the following script to determine who has what permissions and whether they are implicit or explicit.
WITH perms_cte as
(
select USER_NAME(p.grantee_principal_id) AS principal_name,
dp.principal_id,
dp.type_desc AS principal_type_desc,
p.class_desc,
OBJECT_NAME(p.major_id) AS object_name,
p.permission_name,
p.state_desc AS permission_state_desc
from sys.database_permissions p
inner JOIN sys.database_principals dp
on p.grantee_principal_id = dp.principal_id
)
--users
SELECT p.principal_name, p.principal_type_desc, p.class_desc, p.[object_name], p.permission_name, p.permission_state_desc, cast(NULL as sysname) as role_name
FROM perms_cte p
WHERE principal_type_desc <> 'DATABASE_ROLE'
UNION
--role members
SELECT rm.member_principal_name, rm.principal_type_desc, p.class_desc, p.object_name, p.permission_name, p.permission_state_desc,rm.role_name
FROM perms_cte p
right outer JOIN (
select role_principal_id, dp.type_desc as principal_type_desc, member_principal_id,user_name(member_principal_id) as member_principal_name,user_name(role_principal_id) as role_name--,*
from sys.database_role_members rm
INNER JOIN sys.database_principals dp
ON rm.member_principal_id = dp.principal_id
) rm
ON rm.role_principal_id = p.principal_id
order by 1
--- thanks to Jamie Thomson for this ditty
A more few suggestions;
Trace the call using profiler and confirm you are connecting as the user you think you are - sp_who2 might be another way to verify that.
Verify your process is in the correct database. Use the c# connection and run SELECT DB_NAME() - write the result somewhere you can read to confirm.
If this works from one environment but not another I would strongly suspect the connection string.
Check that you do not have authentication errors reported in your SQL logs. These again would indicate possible connection issues.
The conventional wisdom on this error is that it likely reflects a lost or corrupted DLL (in either SQL Server or Visual Studio). And the SOP is to reinstall, though it seems that that does not always work either.
Try to run Visual Studio as administrator
Right click Visual Studio --> Run as Administrator.
Try to connect to the database in SQL Server Management Studio. That'll at least narrow down whether it's a database permission issue or something else. Also, check to confirm that the database exists and you have permission to access it. (Like Joe suggested.)
Assuming that checks out... My googling found a guy with a very similar sounding problem. He said that the runas administrator thing Adel suggested worked for him, but there were other issues that could also cause the error message, including VS not being able to find the IIS virtual server specified in the Web Application Project file (permissions? renamed?). Confirm that the file exists and you have permission to access it.
http://connect.microsoft.com/VisualStudio/feedback/details/317124/system-runtime-interopservices-comexception-in-webapplication-project

Resources