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
Related
I am currently taking CS50, an online introductory course in coding by Harvard. We have just covered SQL and I am trying to attempt the question "Movies" in the problem set now, a description of which can be found here: https://cs50.harvard.edu/x/2020/psets/7/movies/
However, I am not sure how to do this correctly.
For example, for 1.sql, my code is as follows:
SELECT title FROM movies WHERE year = 2008;
I literally wrote only that one line and nothing more in the file "1.sql".
But when I run
$ cat 1.sql | sqlite3 movies.db
in my terminal, nothing happens?
Is this how I am supposed to write code for SQL? Or am I missing some stuff that I should be including (e.g. as headers or what) above my query?
To be clear, I believe I know how to write a query itself but I do not know the "protocol" to write it, if I may. I mean, for example, I am positively sure that "SELECT title FROM movies WHERE year = 2008;" fulfils the question's first requirement.
Some enlightenment would be appreciated!
EDIT 1
Okay first I must apologise to everyone who so very kindly took the time to comment on my post. For some very odd reason, my query did not return any results the first time I ran it. However, when I tried it again, it worked perfectly! Not sure what went wrong honestly, but all is well now! So sorry for wasting everyone's time ):
EDIT 2
Okay I also figured out that the reason why I could not execute my query is that I was in "sqlite3" in my terminal. I was supposed to run the command to execute my query in the main terminal i.e. not when it says "sqlite3". Stupid. I know.
Option 1) you can run "$ cat 1.sql | sqlite3 movies.db" in your normal terminal (not in the sqlite3 mode)
Option 2) you can open sql environment by typing "sqlite3 movies.db" (it will open movies.db if it exists, or create a temporary one if it doesn't exist). Then you can type ".read 1.sql" after the "sqlite>"
Open Browser and test it as mention on your course site
Usage
To test your queries on CS50 IDE, you can query the database by running
$ cat filename.sql | sqlite3 movies.db
where filename.sql is the file containing your SQL query.
Or you can paste them into DB Browser for SQLite’s Execute SQL tab and click ▶.
How can I tranfer data between different DB Servers, this is a daily job,
i.e:
Insert into ServerA..table1
select data from ServerB.table2.
(this is just an example, the real situation is we select data from many servers, and then do some join, then insert into the destination).
We can not use SSIS, we can not use linked server,
How can we do this?
btw, this is a daily job, and the data is huge.
A simple command line BCP script should work for you. For instance:
bcp AdventureWorks2012.Sales.Currency out Currency.dat -T -c -SServer1
bcp AdventureWorks2012.Sales.Currency in Currency.dat -T -c -SServer2
Here's more details
The Sync Framework might be worth a look : http://msdn.microsoft.com/en-us/sync/bb736753.aspx
Look at this question:
SQL backup version is incompatible with this server
The first options from my answer should work for your case
You can use C#.net SqlBulkCopy method.
My answer was converted into comment but I'm adding some more info.
I guess you are looking for this answer on SO:
What is the best way to auto-generate INSERT statements for a SQL Server table?
Once you have the code, just add USE your_databasename_where_to_copy_data at the begining, execute and voila
Edit:
As you want to do it on the fly, using code, try some of the solutions provided on this question on SO. Basically it is similar to your code proposal, with some few differences, as for example:
INSERT INTO bar..tblFoobar( *fieldlist* )
SELECT *fieldlist* FROM foo..tblFoobar
I've done a fair amount of tinkering and searching and the best option seems to be either:
sending output to text and copy/pasting into a text file or Excel OR
outputting to a somewhat unorthodox .rpt file, which I'm not sure what you'd do with--opening it in Excel doesn't preserve formatting present in the original output.
For what seems like a pretty common task, I'm surprised there isn't a simpler way to do this.
Can anyone suggest an easier way to go about this than the two methods I outlined?
Oh, and for what it's worth, I'm working on SQL Server 2008.
How about the BCP utility? http://msdn.microsoft.com/en-us/library/ms189569.aspx
Even through the SSMS GUI, it's still a relatively PITA process:
Plan A:
Tools, Options, Query Results, Results to Text
<= Change output format from "fixed columns" to "delimit by tabs"
At that point, you can "Save results to File", and specify a .csv file
Plan B: fire up your favorite scripting language (like vb.net, for example) and just write a program that does the SQL query and writes the .csv. 10 lines, tops :)
Plan C: Yet another approach is to use some external program to do the query and convert the results for you. SQL Server comes with "BCP". You can easily write a .bat file to invoke it:
http://www.simple-talk.com/sql/database-administration/creating-csv-files-using-bcp-and-stored-procedures/
'Hope that helps
Are you using SQL Server Management Studio? If so, when you open a new query window, you can select to send output to a file. Query Menu -> Results To -> Results to File.
Chris, this is actually super-easy.
If your query results get displayed in the grid (as is the default), just right-click on the grid and choose Save Results As....
From within MSSQL Management Studio, you can right-click on your database and select "Tasks" -> "Export Data". It starts-up a wizard that allows you to pick your data source. On the "Destination" page you can select "Microsoft Excel" or "Flat File Destination". The next page in the wizard allows you to specify data from one or more tables, or a custom query to get your data. If you chose "Flat File Destination" before, the next page allows you to set your own delimiters.
Another option is to pull it into Excel from SQL
Run your query and from the Results tab do Ctrl-a to select all, and paste this into Excel.
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
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 $.