SQL Server 2005 Management Studio - Recover Accidentally Closed Tab - sql-server-2005

Is there a way to do this if an unsaved tab gets accidentally closed?

I was able to recover a query I was working on after accidentally closing the tab. If you actually ran the query, it should be in SQL Server's query cache. Query the query cache and order the results by creation date. More info on the SQL Server query cache:
Modify a query like this one (found at http://msdn.microsoft.com/en-us/library/ee343986(v=SQL.100).aspx)
SELECT cp.objtype AS PlanType,
OBJECT_NAME(st.objectid,st.dbid) AS ObjectName,
cp.refcounts AS ReferenceCounts,
cp.usecounts AS UseCounts,
st.text AS SQLBatch,
qp.query_plan AS QueryPlan
FROM sys.dm_exec_cached_plans AS cp
CROSS APPLY sys.dm_exec_query_plan(cp.plan_handle) AS qp
CROSS APPLY sys.dm_exec_sql_text(cp.plan_handle) AS st;
to get your desired result. The "st.text" column will have the query that was run on the database server.

I also found at MSDN website that it is not possible to recover these files, but I would give a try to this (it worked for me):
Take a look in the folder C:\Users\YOURUSERIDHERE\Documents\SQL Server Management Studio\Backup Files\Solution1 and choose files for date when machine restarted or crash happened. SQLBlog.com
Take a look in the folder C:\Users\”[your username goes here]“\AppData\Local\Temp\ (this wasn't work for me because my .sql files had 0KB and .tmp files had something, but I couldn't find the way to 'extract' code from these .tmp files). Suppose that sometimes can be helpful, depending on reason of system reboot/crash. ayesamson.com

I'm not sure that there is, but using TimeSnapper can be a help to show what was previously in the window.

I don't believe so. I checked on the msdn website and there's a thread about this and the answer is no.

Navigate to My Documents\SQL Server Management Studio Express\Backup Files\Solution1 you will find the Recovered backlogs.This is the only solution.

1.Take a look in the folder C:\Users\YOURUSERIDHERE\AppData\Local\temp, then sort files by date modified and pick the last .sql that has a size greater than 0 bytes. That worked for me.

Unfortunately SSMS currently does not have the Undo Closed Tab feature. I have created the following Connect Item so Microsoft will hopefully add this in a future version: https://connect.microsoft.com/SQLServer/Feedback/Details/1044403

Related

How to use this weird .sql file?

I have a very strange 'reload.sql' file that I need to use to build a database.
It references about 200 XXX.dat files with straight-up readable data (although useless without explanations regarding the meaning of the fields).
I have tried msssql server, mysql workbench (on a server local-hosted on wamp), and directly accessing it through DBeaver and IBConsole, but I cannot manage to execute/build it.
It uses a weird syntax. There are elements like
begin
...
end
go
that hinted me towards T-SQL, but using sqlcmd on it gave me thousands upon thousands of errors regarding keywords.
Specifically, the very first batch of executable lines says
SET OPTION date_order = 'YMD'
go
SET OPTION PUBLIC.preserve_source_format = 'OFF'
go
SET TEMPORARY OPTION tsql_outer_joins = 'ON'
go
SET TEMPORARY OPTION st_geometry_describe_type = 'binary'
go
SET TEMPORARY OPTION st_geometry_on_invalid = 'Ignore'
go
SET TEMPORARY OPTION non_keywords = 'attach,compressed,detach,kerberos,nchar,nvarchar,refresh,varbit'
go
which generates about 150 errors 'Incorrect syntax near OPTION keyword' on its own, and according to google is part of a 'rexx' procedure but 'date_order' should then be 'DATFMT', right?
Another track is that of SyBase, but I cannot for the life of me get it to work (through my trials I did manage to build a .db file, that, well, is useless to me since I can't build it either..).
I've tried accessing it through ODBC pilots as well but none worked (the paradox ODBC did not crash, but said there was an error with a FROM clause, which are generated automatically...).
I need to know a way to build a database from this file or directly access the data it references, which I can't really post since it contains private medical data.
Also what madman came up with this.
The very first google link (for me anyway) against 'st-geometry-describe-option' shows this is a SAP SQL Anywhere database i.e. http://dcx.sybase.com/1200/en/dbadmin/st-geometry-describe-option.html
So I would suggest starting from the SQL Anywhere documentation and you will need to install the database software beforehand.

Recover unsaved SQL query Scripts in Oracle SQL Developer

I know how to do this in SQL Server thanks to this clever bit of code
Use <database>
SELECT execquery.last_execution_time AS [Date Time], execsql.text AS [Script]
FROM sys.dm_exec_query_stats AS execquery
CROSS APPLY sys.dm_exec_sql_text(execquery.sql_handle) AS execsql
ORDER BY execquery.last_execution_time DESC
SOURCE:
Recover unsaved SQL query scripts
Is there a way to do this in Oracle SQL Developer?
This has saved my butt several times.
It is really a problem when you lose unsaved code. For about a
month I have been working on a big procedure, and forgot to save the
code in SVN. If you read this and remember have such unsaved code,
commit it immediately! :) Because everything could happen with your
test db. Ok. you're lucky if you were using Oracle SQL Developer,
because this program has a great feature - it saves your code in its
sql history inspite of eating a big party of your RAM. Open your file
explorer and locate this folder:
C:\Users\%USERNAME%\AppData\Roaming\SQL Developer\SqlHistory
You'll find a lot of XML files, and if you're twice lucky, you'll find
your lost code. It's wonderful. :) . If you're using another program,
try to find a feature like this and maybe it helps you. My condolences
if this post doesn't help you, in any case, try to find something good
among the next: 1) write your code again, and it will be better than
before as you did it once 2) commit your code, so you'll not face such
problem in the future
If you have the privileges then:
SELECT * FROM v$sql
If not then press F8 to bring up a list of previously ran queries.
You can try too, so you can get the unsaved SQL.
View > SQL History, for example, look this picture:
This is using SQLDeveloper's history, like in Matt's answer, but if you want to search through the history files for specific query fragments you remember, they are located as .xml files in /home/username/.sqldeveloper/SqlHistory. From there, enter:
find -type f -mtime -1 -print0 | xargs -0 grep -l <text>
(where -mtime -1 means no sooner than one day ago).
Through View> SQL History or by pressing F8 is a great way to do it, it lets you search for content or database connection, really a good implementation!
SQL History
Use the undo button, as shown in the image

Saving results with headers in SQL Server Management Studio

I am using SQL Server Management Studio.
I wish to save the results of a query to an excel file.
I choose "save as" and then save to CSV file which I can open in excel. All good except I am missing column headers, any ideas how I get them exported?
Tools > Options > Query Results > SQL Server > Results to Text (or Grid if you want) > Include columns headers in the result set
You might need to close and reopen SSMS after changing this option.
On the SQL Editor Toolbar you can select save to file without having to restart SSMS
Try the Export Wizard. In this example I select a whole table, but you can just as easily specify a query:
(you can also specify a query here)
Another possibility is to use the clipboard to copy and paste the results directly into Excel. Just be careful with General type Excel columns, as they can sometimes have unpredictable results, depending on your data. CTL-A anywhere in the result grid, and then right-click:
If you have trouble with Excel's General format doing undesired conversions, select the blank columns in Excel before you paste and change the format to "text".
At least in SQL Server 2012, you can right click in the query window and select Query Options. From there you can select Include Headers for grid and/or text and have the Save As work the way you want it without restarting SSMS.
You'll still need to change it in Tools->Options in the menu bar to have new query windows use those settings by default.
The settings which has been advised to change in #Diego's accepted answer might be good if you want to set this option permanently. Permanently means it'll apply to all future query sessions that you open within SQL Server Management Studio(SSMS). This is usually not the case. Also, changing this setting requires restarting SQL Server Management Studio (SSMS). This is again a not-so-nice experience in case there are many unsaved query session windows open and you are in the middle of debugging something.
SQL Server gives a much slicker option of changing this setting on per session basis which is very quick and convenient. I'm detailing the steps below using query options window:
Right click in query editor window. Now, click Query Options... in the context menu as shown below:
Select Grid under Results node in the left navigation pane. Now, check the Include column headers when copying or saving the results check box as shown below:
That's it. Now, your current query session will start honouring your settings with immediate effect. You don't need restarting SSMS. Also, this setting won't be propagated to any future session either. Effectively, changing this setting on a per session basis is much less noisy.
The same problem exists in Visual Studio, here's how to fix it there:
Go to:
Tools > Options > SQL Server Tools > Transact-SQL Editor > Query Results > Results To Grid
Now click the check box to true: "Include column headers when copying or saving the results"
Select your results by clicking in the top left corner, right click and select "Copy with Headers".
Paste in excel.
Done!
Got here when looking for a way to make SSMS properly escape CSV separators when exporting results.
Guess what? - this is actually an option, and it is unchecked by default. So by default, you get broken CSV files (and may not even realize it, esp. if your export is large and your data doesn't have commas normally) - and you have to go in and click a checkbox so that your CSVs export correctly!
To me, this seems like a monumentally stupid design choice and an apt metaphor for Microsoft's approach to software in general ("broken by default, requires meaningless ritualistic actions to make trivial functionality work").
But I will gladly donate $100 to a charity of respondent's choice if someone can give me one valid real-life reason for this option to exist (i.e., an actual scenario where it was useful).
In SQL Server 2014 Management Studio the setting is at:
Tools > Options > Query Results > SQL Server > Results to Text > Include column headers in the result set.
I also face the same issue. When I used right click in the query window and select Query Options. But header rows does not show up in output CSV file.
Then I logoff the server, login again and run the script. Then it worked.

How to recover the old data from table

I have made an update statement in a table in SQL 2008 which updated the table with some wrong data.
I didn't have a backup for the DB.
It's some important dates which got updated.
Is there anyway where i can recover the old data from the table.
Thanks
SNA
Basically no unless you want to use a commercial log reader and try go through it with a fine tooth comb. No backup of the database can be an 'update resume, leave town' scenario - harsh but it just should not happen.
Andrew basically has called it. I just want to add a few ideas you can consider if you are desperate:
Are there any reports or printouts lying around? Perhaps you can reconstruct the data from there.
Was this data entered via a web application? If so, there is a remote chance you can find the original data in the web server logs, depending upon how the app was constructed, etc.
Does this app interface (pass data to) any other applications? They may have a buffered copy of data...
Can the data be derived from any other existing data? Is there an audit log table, or another date in your schema based on this one, from which you can reconstruct the original date?
Edit:
Some commenters are mentioning that is is a good idea to test your update/delete statements before running them. For this to become habit, it helps if you have an easy method. I usually create my DELETE statements like this:
--delete --select *
from [User]
where UserID=27
To run the select in order to test your query, highlight everything from select onwards. To then run the delete if you are satisfied with the filter criteria, highlight everything from delete onwards. The two dashes in front of delete are so that if the query accidentally gets run, it will just crash due to invalid syntax.
You can use a similar construct for UPDATE statements, although it is not quite as clean.
SQL server keeps log for every transation.So you can recover your modified data from the log as well without backup.
Select [PAGE ID],[Slot ID],[AllocUnitId],[Transaction ID]
,[RowLog Contents 0], [RowLog Contents 1],[RowLog Contents 3],[RowLog Contents 4]
,[Log Record]
FROM sys.fn_dblog(NULL, NULL)
WHERE
AllocUnitId IN
(Select [Allocation_unit_id] from sys.allocation_units allocunits
INNER JOIN sys.partitions partitions ON (allocunits.type IN (1, 3)
AND partitions.hobt_id = allocunits.container_id) OR (allocunits.type = 2
AND partitions.partition_id = allocunits.container_id)
Where object_id=object_ID('' + 'dbo.student' + ''))
AND Operation in ('LOP_MODIFY_ROW','LOP_MODIFY_COLUMNS')
And [Context] IN ('LCX_HEAP','LCX_CLUSTERED')
Here is the artcile, that explains step by step, how to do it.
http://raresql.com/2012/02/01/how-to-recover-modified-records-from-sql-server-part-1/
Imran
Thanks for all the responses.
The problem was actually accidentally ---i missed to select the where condition in the update statement.---Rest !.
It was a quick 5 minutes task --Like just changing the date to test for one customer data--so we didn't think of taking a backup.
Yes of course you are true ..This is a lesson.
Now onwards i will be careful to write "my update statements in a transaction." or "test my update statements"
Thanks once again--for spending your time to give some insight rather ignoring the question since the only answer is "NO".
Thanks
SNA
Always take a backup before major UPDATE statements, even if it's not used, there's the peace of mind
Especially with Red Gate's Object Level Restore, one can restore individual table/row now given a backup file
Good luck, I'd suggest finding an old copy elsewhere (DEV/QA) etc...
Isn't it possible to do a rollback on an UPDATE statement?
Late one but hopefully useful…
If database is in full recovery mode then all transactions are logged in transaction log and can be retrieved. Problem is that this is not natively supported because this is not the main purpose of the transaction log.
Options are:
Commercial tools such as Apex Log (more expensive, more options) or Quest Toad (less expensive, less options for this purpose main focus is on SQL Server management)
Trying to do this yourself, like user1059637 pointed out. Problem with this approach is that it can’t read transaction log backups and is more tedious.
It comes down to how much your data is worth to you in terms of time and $.

Problem with a MS Access query after a "Compact and repair" operation

I have an Access application that use the classical front-end/back-end approach. Yesterday, the backend got corrupted for a reason I don't know. So I opened the backend with Access 2003 and access asked me if I wanted to repair the file, I said yes and it seemed to work.
I can open the database see the tables contents and run most of the queries.
However there is an access query that doesn't work with a specific where clause.
Example :
// This works in the original DB, but not in the compacted one :
SELECT a, b, c
FROM tbl1 INNER JOIN tbl2 ON tbl1.d = tbl2.d
WHERE e = 3 AND tbl2.f = 1;
// This works in both the original and the compacted one :
SELECT a, b, c
FROM tbl1 INNER JOIN tbl2 ON tbl1.d = tbl2.d
WHERE e = 3;
When I try to run the queries, nothing happens. The access process start to use most of the CPU and the GUI stop responding. If I run the query from the query editor, I can use Ctrl+Break to stop the execution. I tried to give the query lot of time and it didn't help.
I've checked the execution plan in showplan.out and it seems correct (at least it should not takes forever to execute)
I tried to compact the DB again. I tried to import the tables in a new DB. I even tried to import the tables and their data in a mdb file that was in a now good state (from a backup).
Anyone have an idea?
Sounds like an index was corrupted and when that happens, it's dropped during the compact. Check for a system table called MSysCompactErrors -- you'll have to show hidden objects and/or system objects in Tools | Options | VIEW.
Never compact a Jet MDB without making a backup beforehand. Because of that rule, the COMPACT ON CLOSE function is completely useless, as it's not cancellable, so you always make sure it's turned off in all MDBs.
I don't know what type of meta data Access brings along when it imports a table from one database into another one. If the meta data is corrupted, importing the table to another database wouldn't necessarily resolve the problem. If practical, you might try creating the tables from scratch in a brand new database and then just exporting and importing (or copying and paste appending) the data into the new database.
I've never seen a table get corrupted like this in such a small database, although with Access anything is possible. Could there be something wrong with the data?
I'd try recreating the query fresh (new name, etc.), and see what happens.
You could even try copying it (even within the same DB or to a brand new one). If that works, the worst case scenario is you have to copy all the objects across to a new DB.
Is there an index on the field tbl2.f?
Also try going into that table in datasheet view, sort tbl2.f in ascending sequence and see if there is anything really strange in the first or last records.
Do you have access to a SQL Server installation? You could use the Upsizing Wizard under the Tools -> Database Utilities menu to copy the data to SQL Server, and see if you get the same problem there.