Truncate SQL Server transaction log file - sql-server

In my local C: drive I have a ldf file for a database that is hosted on one of our servers. I have a local copy of one of the databases that is 1 gb and a ldf (log file) of that database that is 16gb. It is eating up a lot of my local space on my hard drive. I would like to truncate that file. A lot of what I read online is don't, but it seems that they are talking about files on the server that the database is on. That isn't the case here, it is on my local machine.
The location of the file on my machine is:
C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA
How come I have a copy of that log file locally and also that database locally?
How would I go about truncating this file?
Thanks!

Go to the Object Explorer pane in SSMS and right click on the database in question. Choose tasks -> shrink -> files. Change the file type option to Log, click the "Reorganize pages before releasing unused space" option, and set the value to 1 MB. Hit OK.
If this doesn't work, check to see if your database is set up with a Full database recover model. Right click the database and go to properties. Choose Options, and check the Recover model option. Set to simple (if you can!!!), then shrink the logs.

The another option you can try is to use WITH TRUNCATE_ONLY:
BACKUP LOG databasename WITH TRUNCATE_ONLY
DBCC SHRINKFILE ( adventureworks_Log, 1)
but don't try this option in live environment, the far better option is to set database in simple recovery. see the below command to do this:
ALTER DATABASE mydatabase SET RECOVERY SIMPLE
DBCC SHRINKFILE (adventureworks_Log, 1)

Related

Database restore is missing tables

I am using SSMS 2017 and attempting to restore a SQL Server 2016 backup (.bak) file to a new database (the data file and log file names in the original backup are different from the new database I am restoring to), so for example, db1.bak is being used to create a new database called db2 through a restore operation.
After the restore completes, all stored procedures and views are present, but none of the tables are there.
These are the steps I've taken in SSMS to perform the restore:
Right click the Databases folder
Select "Restore Database"
Under the General Page: For "Source" I choose Device and select the db1.bak file, and for "Destination" I enter the name of the new database to be created from the backup (db2)
Under the Files Page I select Relocate all files to folder (both Data and Log folder paths have been pre-populated with the correct names) as have the Logical File Name and the Restore As paths.
Under the Options Page I either select nothing or select Overwrite the existing database (WITH REPLACE).
Once the restore completes "successfully" I expand the newly created db2 and click to expand the tables and receive this error message:
What am I doing wrong?
Here is the script:
USE [master]
RESTORE DATABASE [PdsClone] FROM DISK = N'F:\SQLBackups\PDS_backup_2017_12_12_001015_0199267.bak' WITH FILE = 1, MOVE N'PDS_Data' TO N'E:\Program Files\Microsoft SQL Server\MSSQL13.PDS\MSSQL\DATA\PdsClone.mdf', MOVE N'PDS_Log' TO N'E:\Program Files\Microsoft SQL Server\MSSQL13.PDS\MSSQL\DATA\PdsClone_log.ldf', NOUNLOAD, REPLACE, STATS = 5 GO
UPDATE
I had the server group add another disk to that server and moved the SQL backups there, and I was able to successfully complete the restore this morning. I had previously cleaned off most of the backup files, but could it have been a space issue that prevented the tables from showing up in the restore? Every try it indicated success but no tables. They are there now, and I am thankful for your suggestions and help!
Not really an answer to what happened, but perhaps SSMS was doing something a little buggy as #JeroenMostert suggested.

BACKUP LOG cannot be performed because there is no current database backup

I tried to restore a database but this message showed. How do I restore this database?
Restore of database 'farhangi_db' failed.
(Microsoft.SqlServer.Management.RelationalEngineTasks)
------------------------------ ADDITIONAL INFORMATION:
System.Data.SqlClient.SqlError: BACKUP LOG cannot be performed because
there is no current database backup. (Microsoft.SqlServer.SmoExtended)
Originally, I created a database and then restored the backup file to my new empty database:
Right click on Databases > Restore Database > General : Device: [the
path of back up file] → OK
This was wrong. I shouldn't have first created the database.
Now, instead, I do this:
Right click on Databases > Restore Database > General : Device: [the
path of back up file] → OK
Another cause of this issue is when the Take tail-log backup before restore "Options" setting is enabled.
On the "Options" tab, Disable/uncheck Take tail-log backup before restore before restoring to a database that doesn't yet exist.
Please see below image and apply changes in SqlServer :
first right click on Database --> Task --> Restore --> Select Backup File -->
Finally Apply Change in Options Tab.
Make sure there is a new database.
Make sure you have access to your database (user, password etc).
Make sure there is a backup file with no error in it.
In our case it was due to the Recovery Model on the primary database having been changed after we did the backup in preparation for setting up log shipping.
Ensuring the Recovery Model was set to Full Recovery before doing the backup and setting up log shipping resolved it for us.
You can use following SQL to restore if you've already created database
RESTORE DATABASE [YourDB]
FROM DISK = 'C:\YourDB.bak'
WITH MOVE 'YourDB' TO 'C:\YourDB.mdf',
MOVE 'YourDB_Log' TO 'C:\YourDB.ldf', REPLACE
Another cause for this is if you have the same database restored under a different name.
Delete the existing one and then restoring solved it for me.
I fixed my error on restoring to non-existing DB from SQL 2008 to SQL 2014 by putting a check mark on Relocating to the new SQL2014 folder location.
I just deleted the existing DB that i wanted to override with the backup and restored it from backup and it worked without the error.
I am not sure whether the database backup file, you trying to restore, is coming from the same environment as you trying to restore it onto.
Remember that destination path of .mdf and .ldf files lives with the backup file itself.
If this is not a case, that means the backup file is coming from a different environment from your current hosting one, make sure that .mdf and .ldf file path is the same (exists) as on your machine, relocate these otherwise.
(Mostly a case of restoring db in Docker image)
The way how to do it:
In Databases -> Restore database -> [Files] option -> (Check "Relocate all files to folder" - mostly default path is populated on your hosting environment already)
In case the problem still exists go to Restoration Database page and Check "Restore all files to folder" in "Files" tab This might help
In my case I am restoring a SQL Server 2008 R2 Database to SQL Server 2016
After selecting the file in the General tab, you should go to the Options tab and do 2 things:
You must activate Overwrite existing database
You must deactivate end of record copy
Simply you can use this method:
If you have a database with same name:
WIN+R -> services.msc -> SQL SERVER(MSSQLSERVER) -> Stop
Go to your MySQL Data folder path and delete previews database files
Start sql service
Right click on database and select Restore database
in Files tab change Data file folder and Log file folder
Click on OK to restore your database
my problem was solved with this method
BY...
Click Right Click On Your Database The Press tasks>Back Up and take a back up from your database before restore your database i'm using this way to solve this Problem

SQL-Server: The backup set holds a backup of a database other than the existing

I am trying to restore a SQL Server backup file for my database, but it is throwing an error as follow:
The backup set holds a backup of a database other than the existing
My database in SQL Server 2008 and the backup file is in 2005.
What can be the problem?
I too came across this issue.
Solution :
Don't create an empty database and restore the .bak file on to it.
Use 'Restore Database' option accessible by right clicking the "Databases" branch of the SQL Server Management Studio and provide the database name while
providing the source to restore.
Also change the file names at "Files" if the other database still exists. Otherwise you get "The file '...' cannot be overwritten. It is being used by database 'yourFirstDb'".
Either:
1) Use WITH REPLACE while using the RESTORE command (if using the GUI, it is found under Options -> Overwrite the existing database (WITH REPLACE)).
2) Delete the older database which is conflicting and restore again using RESTORE command.
Check the link for more details.
First create a blank database of the same name. Then go for the restore option
Under Options on the left pane don't forget to select
Overwrite the existing database
Preserve the replication settings
That's it
I was facing same problem and found the solution by doing this, using SSMS 2014
Just select the Option Overwrite the existing database(WITH REPLACE)
This causes always due to version incompatibility.
follow these steps to solve:
Step 1: Create a database with your preferred name. (In our case AdventureWorks)
Step 2: Write click on the database and click on Tasks >> Restore >> Database…
Step 3: On the restore screen go to third selection of Options. Now select the checkbox “Overwrite the existing database (WITH REPLACE)”
Step 4: Click OK. It should successfully restore the database.
Note: When you restore a database WITH REPLACE it will overwrite the old database.
USE [master];
GO
CREATE DATABASE db;
GO
CREATE DATABASE db2;
GO
BACKUP DATABASE db TO DISK = 'c:\temp\db.bak' WITH INIT, COMPRESSION;
GO
RESTORE DATABASE db2
FROM DISK = 'c:\temp\db.bak'
WITH REPLACE,
MOVE 'db' TO 'c:\temp\db2.mdf',
MOVE 'db_log' TO 'c:\temp\db2.ldf';
Simple 3 steps:
1- Right click on database → Tasks → restore → Database
2- Check Device as source and locate .bak (or zipped .bak) file
3- In the left pane click on options and:
check Overwrite the existing database.
uncheck Take tail-log backup before restore
check Close existing connection to destination database.
Other options are really optional (and important of course)!
If you are using the script approach and have an error concerning the LDF and MDF files, you can first query the the backup file for the logical names (and other details) of files in the backup set, using the following:
-- Queries the backup file for the file list in backup set, where Type denotes
-- type of file. Can be L,D,F or S
-- info: https://learn.microsoft.com/en-us/sql/t-sql/statements/restore-statements-filelistonly-transact-sql
RESTORE FILELISTONLY FROM DISK = 'C:\Temp\DB_backup.bak'
GO
You will get results similar to the following:
And then you can use those logical names in the queries:
-- Script assumes you want MDF and LDF files restored on separate drives. Modify for your scenario
RESTORE DATABASE DB
FROM DISK='C:\Temp\DB_backup.bak'
WITH REPLACE,
MOVE 'DB' TO 'E:\MSSQL\Data\DB.mdf', -- "DB" is the mdf logical name from query above
MOVE 'DB_log' TO 'F:\MSSQL\Logs\DB.ldf'; -- "DB_log" is LDF logical name from query above
More info on RESTORE FILELISTONLY can be found from the SQL Server docs.
Its because the .mdf and .ldf Files from the original Db were locate at maybe c:\programFile\.... and this info is saved in the Backup!
If you create the same DB on a different SQL Server where the installation is on c:\program Files (x86)\ .... you can not restore as usually. You need to relocate the path for .mdf and .ldf Files.
Therefore:
Create a empty DB on the new Server
Right click on the empty Db > Tasks > Restore > Database > click Device select your .bak Files > Select Db to restore into
click on Files at left side > Select "Relocate all Files to Folder"
click Options on the left site > click on Overwrite
Done!
Hope it helps!
I had ran into similar problem today. Tried all the above solutions but didn't worked. So posting my solution here.
Don't forget to uncheck Tail-long Backup before restore
Hope it help others too!
Also as important is to make sure that, your database name matches the data base name in the backup you are trying to restore. If it does not match, you will get the same error.
system.data.sqlclient.sqlerror:The backup set holds a backup of a database other than the existing 'Dbname' database
I have came across to find soultion
Don't Create a database with the same name or different database name !Important.
right click the database | Tasks > Restore > Database
Under "Source for restore" select "From Device"
Select .bak file
Select the check box for the database in the gridview below
To DataBase: "Here You can type New Database Name" (Ex:DemoDB)
Don't select the Existing Database From DropDownlist
Now Click on Ok Button ,it will create a new Databse and restore all data from your .bak file .
you can get help from this link even
Hope it will help to sort out your issue...
Before doing anything else, confirm if your backup is Full or Differential. If you're trying to create a new database out of a differential backup, no matter what you do you will encounter the error.
Same issue with me.The solution for me is:
Right click on the database.
Select tasks, select restore database.
Click options on the left hand side.
Check first option OverWrite the existing database(WITH REPLACE).
Go to General, select source and destination database.
Click OK, that's it
I was just trying to solve this issue.
I'd tried everything from running as admin through to the suggestions found here and elsewhere; what solved it for me in the end was to check the "relocate files" option in the Files property tab.
Hopefully this helps somebody else.
Some of you have highly over complicated this. I found this to be extremely simple.
1) Create a database with the same name as your .bak file database name !Important
2) right click the database | Tasks > Restore > Database
3) Under "Source for restore" select "From Device"
4) Select .bak file
5) Select the check box for the database in the gridview below
6) Under "Select a Page" on the right Select "Options"
7) Select the checkbox labeled "Preserve the replication settings(WITH KEEP_REPLICATION)
Now Go back to the General page and click OK to restore the database...That is it.
I had to create new db on my local for testing & i had a back up from my prod. I created the db first and tried to run the BAK on top of the new db which produced this error for me. I deleted the db and restored it while sourcing the new db name in the restore screen itself. The db was automatically created on restore.
I got work done through alternate way, using Generate scripts. That did work for me as Backup-Restore didn't help to resolve the issue due to same error.
In the Options, change the "Restore As" file name to the new database mdf and ldf. It is referencing the source database .mdf and .ldf files.
You can restore to a new DB, verify the file name syntax, it ll be in the log file, for the new SQL version ll be a "_log" suffix
ad check the overwrite the existing database flag in option tab
Fabio
This helped me to import the back-up file from the system drive
Create a database with the same name(preferably) as your .bak file database name
Right click the database > Tasks > Restore > Database
Under "Source for restore" select "From Device"
Select the .bak file selecting the path from the system
Select the check box for the database in the list box below
Under "Select a Page" on the right Select "Options"
Select the checkbox labeled "Preserve the replication settings(WITH KEEP_REPLICATION)
Select the checkbox for Overwrite the existing database(WITH REPLACE)
Now Go back to the General page and click OK to restore the database...
Im sure this problem is related to the files and folders permissions.
I was trying to restore a production database to a staging database on the same server.
The only thing that worked in my case was restore to a new blank database. This worked great, did not try to overwrite production files (which it would if you just restore production backup file to existing staging database). Then delete old database and rename - the files will keep the new temp name but in my case that is fine.
(Or otherwise delete the staging database first and then you can restore to new database with same name as staging database)
instead of click on Restore Database click on Restore File and Filegroups..
thats work on my sql server
I had the same issue but on PS. I leave it here in case someone is trying to do the same
Restore-SqlDatabase -ServerInstance "<your instance name>" -Database "<your db name>" -BackupFile "<backup file route>.bak" -ReplaceDatabase
remember to use Set-ExecutionPolicy Unrestricted -Force and import import-module sqlps. Don't forget to set back your Execution Policy back to restricted once you are done.
Usually dealing with .bak files are coming with headaches, a more straight forward way is using sqldump files to transfer databases.
Generate script of current database you want to move or copy.
Instead of entire database, select All Tables.
From the option menu choose save as script, and click on advance button and set the following configs (I am suing MSSQL 2016):
Now, where you want to import these data, create a new database, switch to this new database (I mean set it as default)
Finally run the script, all table and data will be imported.
Good Luck.
List item

Is there any way to undelete a SQL server database and stored procedures?

Is there any way to undelete a SQL server database and stored procedures?
Edit:
No I don't have a backup. That is the reason I need help
Restore from backup.
You do have a backup, right?
Edit:
I'm assuming you probably did a right-click, "Delete" from SQL Management Studio? If so, that actually does a "drop" of the database, which literally removes the files from the hard drive. If this is the case, you'll have to restore from your latest backup (if you have one).
If you just did a "detach", then the MDF and LDF files are still on the hard drive, and you can simply attach them.
How exactly have you deleted it.
If you haven't made any changes to you disks file system since then (and not defraged) then its possible the file will still be sitting on the disk as windows doesn't delete the file completely, just the File Handle.
Have a look at something like this and you may be able to recover the .mdf/.ldf files from your HD.
http://www.undelete.com/file-recovery.aspx
If not, you'll have to restore from your last back.
And if you don't have a backup... you're screwed.
If you accidently deleted the database in SQL Server Management Studio by right clicking and hitting delete in a hurry and you have no backup then there might still be a chance of getting back the database:
Don't do any save / delete file operations on the disk where the database file was stored, browsing should be ok.
Find the location where the .mdf file used to be. In my case it was "c:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS2012\MSSQL\DATA". If you have multiple databases you can right click on an existing one, select properties and files. Find the location entry in the listbox under path (select and ctrl+c to copy it)
Download a portable undelete program e.g. Recuva to a USB drive/stick (unzip) and run it from the USB drive/stick.
Set the copied path as the "search location" in your undelete program (ctrl+v), recover "YOURDATABASE.mdf" and "YOURDATABASE_log.ldf" to the USB drive.
Copy the files from USB drive/stick to the original location.
In SQL Server Management Studio right click on "Databases" select "Attach.." click Add, select "YOURDATABASE.mdf".
Get some coffee and think about backups :-)
Did you drop the database or detach it ? If you've detached it then just reattach it again from the mdf and ldf files.

How to recover database from MDF in SQL Server 2005?

I have an MDF file and no LDF files for a database created in MS SQL Server 2005. When I try to attach the MDF file to a different SQL Server, I get the following error message.
The log cannot be rebuilt because there were open transactions/users when the database was shutdown, no checkpoint occurred to the database, or the database was read-only. This error could occur if the transaction log file was manually deleted or lost due to a hardware or environment failure.
I would like to accomplish any one of the following options:
Attach the database without data loss (unlikely but would save me some time).
Attach the database with data loss (whatever transactions were open are lost).
Recover the schema only (no data) from the MDF file.
What SQL commands can I try to get my database going again?
I found the following document on Experts Exchange.
patrikt:
You will have data loss but it can be done.
1. Detach database and move your mdf to save location.
2. Create new databse of same name, same files, same file location and same file size.
3. Stop SQL server.
4. Swap mdf file of just created DB to your save one.
5. Start SQL. DB will go suspect.
6. ALTER DATABASE yourdb SET EMERGENCY
7. ALTER DATABASE yourdb SET SINGLE_USER
8. DBCC CHECKDB (yourdb, REPAIR_ALLOW_DATA_LOSS)
9. ALTER DATABASE yourdb SET MULTI_USER
10. ALTER DATABASE yourdb SET ONLINE
Here are details that cover parts 2) and 3) in case re-creating log doesn’t work which can happen if MDF file is corrupted.
You can recover data and structure only by reading MDF file with some third party tool that can de-code what’s written as binary data but even with such tools you can’t always do the job completely.
In such cases you can try ApexSQL Recover. From what I know this is the only tool that can do this kind of job but it’s quite expensive.
Much better idea is to try to recover these from any old backups if you have any.
FROM a post at SQL Server Forums Attaching MDF without LDF:
If you want to attach a MDF without LDF you can follow the steps below
It is tested and working fine
Create a new database with the same name and same MDF and LDF files
Stop sql server and rename the existing MDF to a new one and copy the original MDF to this location and delete the LDF files.
Start SQL Server
Now your database will be marked suspect 5. Update the sysdatabases to update to Emergency mode. This will not use LOG files in start up
Sp_configure "allow updates", 1
go
Reconfigure with override
GO
Update sysdatabases set status = 32768 where name = "BadDbName"
go
Sp_configure "allow updates", 0
go
Reconfigure with override
GO
Restart sql server. now the database will be in emergency mode
Now execute the undocumented DBCC to create a log file
DBCC REBUILD_LOG(dbname,'c:\dbname.ldf') -- Undocumented step to
create a new log file.
(replace the dbname and log file name based on ur requirement)
Execute sp_resetstatus
Restart SQL server and see the database is online.
UPDATE: DBCC REBUILD_LOG does not existing SQL2005 and above. This should work:
USE [master]
GO
CREATE DATABASE [Test] ON
(FILENAME = N'C:\MSSQL\Data\Test.mdf')
FOR ATTACH_REBUILD_LOG
GO
have you tried to ignore the ldf and just attach the mdf:
sp_attach_single_file_db [ #dbname = ] 'dbname' , [ #physname = ] 'physical_name'
i don't know exactly what will happen to your open transactions (probably just lost), but it might get your data back online.
-don
See here : Rebuild master and restore system databases from complete disk failure which has a very nice explanation
Just had this problem myself, but none of the above answers worked for me.
But instead, I found this which worked a treat and so I thought I'd share this for everyone else:
http://www.kodyaz.com/articles/sql-server-attach-database-mdf-file.aspx
Found a another way that works completely:
Create new database with same name to default database location.
Stop SQL server.
Copy old mdf file to overwrite newly created mdf file and delete new ldf file
Start SQL Server, database will be in emergency mode
Detach the emergency mode database
Copy original ldf file to default database location (where new LDF file as created and deleted under step 3 above.
Attach the database MDF file.
I got a working database after trying all of the above that failed for me.
I hope it is easy to do so,
Open SQL Server
Click New Query
Execute the following query
sp_attach_single_file_db #dbname='dbname',#physname='C:\Database\dbname.MDF'
Where dbname is you want to show in Object Explorer, where #physname is the local filepath location of your mdf file.
Hope it will help someone, i done by above, got both structure and also data.
Tested in Sql Server 2000 and 2008. In Sql Server 2000 it is not working, but works perfectly in 2008.

Resources