Recover Deleted Rows in OUTPUT clause - sql

I ran the following query in SSMS without capturing the result in table variable. Is there any way I can get the deleted row using temporay created DELETED table? I have not closed the SQL session. I am in the same session where I have ran the following query.
delete from [AdventureWorksDW2014].[dbo].[FactCallCenter]
output deleted.*
where FactCallCenterID = 119

No, the resultset from OUTPUT without INTO goes straight to the client like any other SELECT. So you should be able to see the in SSMS if you have not run another query since.
If you need to undelete rows, restore from backup. Failing that, find software that can replay the transaction log. Make sure the transaction log is not truncated by backup software in the interim.

Related

Is it ok to KILL this DELETE query?

I ran a query to delete around 4 million rows from my database. It ran for about 12 hours before my laptop lost the network connection. At that point, I decided to take a look at the status of the query in the database. I found that it was in the suspended state. Specifically:
Start Time SPID Database Executing SQL Status command wait_type wait_time wait_resource last_wait_type
---------------------------------------------------------------------------------------------------------------------------------------------------
2018/08/15 11:28:39.490 115 RingClone *see below suspended DELETE PAGEIOLATCH_EX 41 5:1:1116111 PAGEIOLATCH_EX
*Here is the sql query in question:
DELETE FROM T_INDEXRAWDATA WHERE INDEXRAWDATAID IN (SELECT INDEXRAWDATAID FROM T_INDEX WHERE OWNERID='1486836020')
After reading this;
https://dba.stackexchange.com/questions/87066/sql-query-in-suspended-state-causing-high-cpu-usage
I realize I probably should have broken this up into smaller pieces to delete them (or even delete them one-by-one). But now I just want to know if it is "safe" for me to KILL this query, as the answer in that post suggests. One thing the selected answer states is that "you may run into data consistency problems" if you KILL a query while it's executing. If it causes some issues with the data I am trying to delete, I'm not that concerned. However, I'm more concerned about this causing some issues with other data, or with the table structure itself.
Is it safe to KILL this query?
If you ran the delete from your laptop over the network and it lost connection with the server, you can either kill the spid or wait when it will disappear by itself. Depending on the ##version of your SQL Server instance, in particular how well it's patched, the latter might require instance restart.
Regarding the consistency issues, you seem to misunderstand it. It is possible only if you had multiple statements run in a single batch without being wrapped with a transaction. As I understand, you had a single statement; if that's the case, don't worry about consistency, SQL Server wouldn't have become what it is now if it would be so easy to corrupt its data.
I would have rewritten the query however, if T_INDEX.INDEXRAWDATAID column has NULLs then you can run into issues. It's better to rewrite it via join, also adding batch splitting:
while 1=1 begin
DELETE top (10000) t
FROM T_INDEXRAWDATA t
inner join T_INDEX i on t.INDEXRAWDATAID = i.INDEXRAWDATAID
WHERE i.OWNERID = '1486836020';
if ##rowcount = 0
break;
checkpoint;
end;
It definitely will not be any slower, but it can boost performance, depending on your schema, data and the state of any indices the tables have.

sql server update affects 0 records but fills transaction log

I have a SQL statement that updates records in a table if the query returns any records. The query only returns records if they need to be updated. When I run the select on the query I get no records so when the update runs there should be no records updated.
The problem I'm having is that the query in the stored procedure won't finish becuase the transaction log fills up before the query can complete. I'm not concerned about the transaction log filling up right now.
My question is, if there no records are being updated then why is anything being written to the transaction log?
We need more information before this problem can be solved ...
Remus has a great idea to look at the entries in the log file.
Executing DBCC SQLPERF(logspace) will give you how full the log file is.
Clear the log file using a transaction log backup. This is assuming the recovery model is FULL and a FULL backup has been done.
Re-run the update stored procedure. Look at the transaction log file entries.
A copy of the stored procedure and table definitions would be great. Looking for other processes (sp_who2) during then execution that might fill the log is another good place to look.
Any triggers that might cause updates, deletes or inserts can add to the log file size, suggested by Martin.
Good luck.
Looks like the issue was in the join. It was tyring to join so many records that tempdb was filling up to the point there was no more space on the drive.

SQL Replication error - row was not found at the Subscriber

We are trying to setup replication on a SQL Server 2005 database. We have followed some instructions for the past year, and all has been fine. Recently, it started failing (Development environment, so every week we rebuild the database.. and apply replciation).
We follow a set of steps, snap shot gets generated.. and applied to the replicated database. All fine. No errors.
We then add a new row to the source database, and bang! Error.
Command attempted:
if ##trancount > 0 rollback tran
(Transaction sequence number: 0x000004BE00000558000100000000, Command ID: 1)
Error messages:
The row was not found at the Subscriber when applying the replicated command. (Source: MSSQLServer, Error number: 20598)
We're inserting a row, but it's complaining that the row isn't on the subscriber. That's right, though. We want it to replicate the insert to the subscriber...
When we do a SELECT COUNT(*) on both the source and the destination, the row count is the same, until we do the INSERT, at which point, the source incriments, but the destination remains the same....
Any ideas where we can start looking?
Ugh... this error sucks. When you say that you inserted a row, I assume that you inserted it at the publisher. That's not going to work; replication delivers commands serially. That is, it won't replicate the fact that you inserted the missing row until it gets past your current error.
So, here's where we start. In the error message, we see an transaction sequence number. We can use that to determine the primary key of the missing row. At the distributor, there's a stored procedure called sp_browsereplcmds. You can plug in the transaction sequence number in for both the #xact_seqno_start and #xact_seqno_end parameters. You'll also see a command_id parameter in the stored procedure; this corresponds to the Command ID in your error message. Try executing the procedure with just those parameters specified. It should give you the command that it's trying to execute at the subscriber. From there, you can tell the primary key of the row that it's either trying to update or delete. You can then insert a row with that primary key at the subscriber and replication will move on.
Alternatively, you could drop this article from this subscriber, re-add it, and re-initialize that article. It's a bit more intense on the server, but is a lot less fiddly.
This is due to data corruption on publisher database,we faced the same replication errors,when we ran DBCC check DB with allow data loss.
Finally We tried doing RCA like
1.) Checking for storage errors by doing CHKDSK in offline mode
2.)Purging the table if it has a lot of data ..in our case we had 40 million rows.
The issue was gone after doing Purging data in our case

Master database DB STARTUP problem

I have a SQL Server 2008 database and I have a problem with this database that I don't understand.
The steps that caused the problems are:
I ran a SQL query to update a table called authors from another table called authorAff
The authors table is 123,385,300 records and the authorsAff table is 139,036,077
The query took about 7 days executing but it didn't finish
I decided to cancel the query to do it another way.
The connection on which I was running the query disconnected suddenly so the database became in recovery until the query cancels
The server was shut down many times afterwards because of some electricity problems
The database took about two days and then recovered.
Now when I run this query
SELECT TOP 1000 *
FROM AUTHORS WITH(READUNCOMMITTED)
It executes and returns the results but when I remove WITH(READUNCOMMITTED) hint it gets locked by a process running on the master database that appears only on the Activity Monitor with Command [DB STARTUP] and no results show up.
so what is the DB STARTUP command and if it's a problem, how can I solve it?
Thank you in advance.
I suspect that your user database is still trying to rollback the transaction that you canceled. A general rule of thumb indicates that it will take about the same amount of time, or more, for an aborted transaction to rollback as it has taken to run.
The rollback can't be avoided even with the SQL Server stops and starts you had.
The reason you can run a query WITH(READUNCOMMITTED) is because it's ignoring the locks associated with transaction that is rolling back. Your query results are considered unreliable, but ironically, the results are probably what you want to see since the blocking process is a rollback.
The best solution is to wait it out, if you can afford to do so. You may be able to find ways to kill the blocking process, but then you should be concerned with database integrity.

SQL Server 2005: Why would a delete from a temp table hang forever?

DELETE FROM #tItem_ID
WHERE #tItem_ID.Item_ID NOT IN (SELECT DISTINCT Item_ID
FROM Item_Keyword
JOIN Keyword ON Item_Keyword.Keyword_ID = Keyword.Record_ID
WHERE Keyword LIKE #tmpKW)
The Keyword is %macaroni%. Both temp tables are 3300 items long. The inner select executes in under a second. All strings are nvarchar(249). All IDs are int.
Any ideas? I executed it (it's in a stored proc) for over 12 minutes without it finishing.
Anything that has a lock on the table could prevent the query from proceeding. Do you have any other sessions open in SSMS where you have done something to one of the tables?
You can also use the system sproc sp_who2 to see if there are any locks open. look in the column BlkBy and see if anything is hanging on a lock held by another process.
The classic case where SQL Server "hangs" is when you open a transaction but don't commit or rollback. Don't get so wrapped up in your actual delete (unless you are working with a truly huge dataset) that you fail to consider this possibility.
When i run into issues like this i fire up SQL Heartbeat and it can show me what is causing the conflict. This also shows deadlocks related to transactions that were not closed correctly as Mark states above.
Sounds like you might want to read up on deadlocking...
** Ignore my answer - I'm leaving it up so that Dr. Zim's comment is preserved, but it is incorrect **