How to import .bak file to using mssql on vscode? - sql-server

I use Linux. But I work on sql, mssql. So i only find a way to use mssql on linux with vscode's sql extension. So in this extension i can find how to create db or table etc. But i can not find how to import an exist db. How can i handle this?
Thanks in advance.

Restoring databases in MS SQL is covered extensively in the documentation and even on SO:
How to: Restore Files and Filegroups (Transact-SQL)
RESTORE Statements (Transact-SQL) - SQL Server
Import .bak file to a database in SQL server
Migrate a SQL Server database from Windows to Linux using backup and restore
If you are using vscode then you are only looking for the SQL syntax/commands to complete the task, so ignore the solutions that use management studio and the UI.
The complicating factor for many in SQL Backup/Restore operations is that the paths that you specify in the SQL commands to perform the operations is relative to the server, NOT to your workstation where you are executing the command from.
So the first step is to copy the backup file to a location that the database engine has file system level access to, then use that path in the SQL scripts.
This is an example:
RESTORE DATABASE YourDB
FROM DISK = '/var/opt/mssql/backup/YourDB.bak'
WITH MOVE 'YourDB' TO '/var/opt/mssql/data/YourDB.mdf',
MOVE 'YourDB_Log' TO '/var/opt/mssql/data/YourDB_Log.ldf'
But read through the docs for the specific restoration sequence and parameters for your needs.
If you are unsure of the current filepaths in use, you can query them from the database:
SELECT
MDF.database_id,
MDF.name,
MDF.physical_name as data_file,
LDF.physical_name as log_file,
db_size_mb = CAST((MDF.size * 8.0)/1024 AS DECIMAL(8,2)),
log_size_mb = CAST((LDF.size * 8.0 / 1024) AS DECIMAL(8,2))
FROM (SELECT * FROM sys.master_files WHERE type_desc = 'ROWS' ) MDF
JOIN (SELECT * FROM sys.master_files WHERE type_desc = 'LOG' ) LDF ON MDF.database_id = LDF.database_id
database_id
name
data_file
log_file
db_size_mb
log_size_mb
1
master
C:\Program Files\Microsoft SQL Server\MSSQL15.TEST\MSSQL\DATA\master.mdf
C:\Program Files\Microsoft SQL Server\MSSQL15.TEST\MSSQL\DATA\mastlog.ldf
5.38
2.00
2
tempdev
C:\Program Files\Microsoft SQL Server\MSSQL15.TEST\MSSQL\DATA\tempdb.mdf
C:\Program Files\Microsoft SQL Server\MSSQL15.TEST\MSSQL\DATA\templog.ldf
8.00
8.00
3
modeldev
C:\Program Files\Microsoft SQL Server\MSSQL15.TEST\MSSQL\DATA\model.mdf
C:\Program Files\Microsoft SQL Server\MSSQL15.TEST\MSSQL\DATA\modellog.ldf
8.00
8.00
4
MSDBData
C:\Program Files\Microsoft SQL Server\MSSQL15.TEST\MSSQL\DATA\MSDBData.mdf
C:\Program Files\Microsoft SQL Server\MSSQL15.TEST\MSSQL\DATA\MSDBLog.ldf
19.69
28.81
5
MyApp
D:\SQL Server\MyApp.mdf
L:\SQL Server\MyApp_log.ldf
392.00
19912.00

Related

SQL Server: attach database without a log file

I have uninstalled my SQL Server 2019 and installed SQL Server 2022 Express. All my databases are under:
C:\Program Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER\MSSQL\DATA
My new location is:
C:\Program Files\Microsoft SQL Server\MSSQL16.MSSQLSERVER\MSSQL\DATA
Attaching a database directly from the old location results in:
Unable to open the physical file "C:\Program Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER\MSSQL\DATA\DBName.mdf". Operating system error 5: "5(Access is denied.)".
I then copied the .mdf file to the new location. But trying to attach it from the new location, I get a similar error, but for the log file:
Unable to open the physical file "C:\Program Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER\MSSQL\DATA\DBName_log.ldf". Operating system error 5: "5(Access is denied.)".
I can't copy the log file into the new location because I don't have enough space on my HD.
Any idea?
Thanks
Operating system error 5: "5(Access is denied.)".
SQL Server locks down the data folder with NTFS ACLs. So you can fix this by taking ownership of the folder and files and granting full control to the other SQL Server instance.
SQL Server disables permissions inheritance on the files, so you need to grant full control to the other SQL instance to each file. And if you're connected using Windows Integrated Auth, you'll also need to grant yourself full control over the files.
In my test, after granting full control over the mdf and ldf to 'NT Service\MSSQLSERVER' and to my windows user, I was able to run
CREATE DATABASE [Foo]
ON (FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL15.SQLEXPRESS\MSSQL\DATA\Foo.mdf' ),
(FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL15.SQLEXPRESS\MSSQL\DATA\Foo_log.ldf' )
for attach
from the default instance.
You can also move (not copy) the files without needing additional space.

SQL Server database export to another computer

I use SQL Server Managment Studio, SQL Server Express. I gererate a script with schema and data from Task -> Generate Script. And I try to import this script in other computer with the same SQL Server but this giving me error :
Directory lookup for the file "C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\WHFM.mdf" failed with the operating system error 3 (The system cannot find the path specified.).
What should I have done to import /export entire database from one PC to another .
If you read through the first few lines of the script, you will see code that specifies the name and location of the files of the database. In your case look for 'C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\WHFM.mdf' in your script. Then look at the directory structure of the target machine. You will need to either:
1. create a directory 'C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\' and make sure the sql instance on the machine has RW access to that directory.
or much better,
2. Modify the script to put the file in a location that the target server wants to put files.
In regards to #2, you can have the target server give you a hint as to where to put files by right-clicking on "Databases" in Microsoft SQL Server Management Studio and create a script to create a database. The directory of the files in the create database script from the target-server should show you what to do.

Copying .mdf file from app_data folder to default localhost folder

My friend gave me a database file: record.mdf. I copied that .mdf file to my app_data folder and I can access it.
However, the connection string contains absolute path:
AttachDbFilename="C:\Users\Dell\Documents\Visual Studio 2010\Projects\WebApplication2\WebApplication2\App_Data\record.mdf"
But I want it to connect using:
Data Source=localhost\SQLEXPRESS;
How do I copy .mdf file to SQL Server's local folder, so that the connection string does not use an absolute path to the database?
I am using Visual Studio 2010. I do not have SQL Server Management Studio.
Step 1: you need to find out your SQL Server's data directory. This will be something like
C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Data
by default (for SQL Server 2008 R2 Express) - it might be slightly different in your case, depending on how you installed your SQL Server Express (and which version you have).
Step 2: copy that record.mdf file to that directory
Step 3: attach it to your SQL Server Express instance - using sqlcmd if you don't have Mgmt Studio at hand:
c:\> sqlcmd -S .\SQLExpress
Then at the sqlcmd prompt, type in:
USE [master]
GO
CREATE DATABASE record ON
(FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Data\record.mdf' )
FOR ATTACH_REBUILD_LOG;
GO
This will attach the .mdf file as your new "logical" database record to your SQL Server Express instance, and it will rebuild the missing transaction log file (.ldf) in the process.
From now on, you can use
server=.\SQLEXPRESS;Database=record;Integrated Security=SSPI;
as your connection string to connect to your database
Rather than copying it to the SQL server local folder, you can access it from the App_Data directory using |DataDirectory|\record.mdf
Documentation: http://msdn.microsoft.com/en-us/library/ms247257(v=vs.80).aspx

System.Data.SqlClient.SqlError: There is already an object named 'sysnsobjs' in the database. (Microsoft.SqlServer.Express.Smo)

I am getting SQL restore error , please help.
Im using Managment studio. Im trying to restore my database(say for example database name XYZ) taken backup from SQL 2000 server and trying to restore to 2008 R2 database XYZ. The exact error string is during Restore failed is
Restore failed for Server 'MACHINENAME\INSTANCENAME'. (Microsoft.SqlServer.SmoExtended)
For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=10.50.1617.0+((KJ_RTM_GDR).110422-1125+)&EvtSrc=Microsoft.SqlServer.Management.Smo.ExceptionTemplates.FailedOperationExceptionText&EvtID=Restore+Server&LinkId=20476
Program Location:
at Microsoft.SqlServer.Management.Smo.Restore.SqlRestore(Server srv)
at Microsoft.SqlServer.Management.SqlManagerUI.SqlRestoreDatabaseOptions.RunRestore()
===================================
System.Data.SqlClient.SqlError: There is already an object named 'sysnsobjs' in the database. (Microsoft.SqlServer.Smo)
For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=10.50.1617.0+((KJ_RTM_GDR).110422-1125+)&LinkId=20476
Program Location:
at Microsoft.SqlServer.Management.Smo.ExecutionManager.ExecuteNonQueryWithMessage(StringCollection queries, ServerMessageEventHandler dbccMessageHandler, Boolean errorsAsMessages)
at Microsoft.SqlServer.Management.Smo.BackupRestoreBase.ExecuteSql(Server server, StringCollection queries)
at Microsoft.SqlServer.Management.Smo.Restore.SqlRestore(Server srv
ODBC SQL server Driver ERROR There is a already an object named
'sysnobjs' in database
While restoring SQL Server 2000 user database to SQL Server 2008 R2 version.
Please let me know whether Microsoft SQL Server 2000 database backup and restore it to SQL Server 2008 is allowed?
If it is not so , is there any work-around for this issue?
In options, while you are in the box that has you choose where your backup is to restore, choose overwrite existing database option. That should get rid of that error and allow you to restore that backup.
After selecting the Backup File to restore in the General Tab, Go to the Options Tab.
Select "Överwrite the existing database (WITH REPLACE)"
Then, in the "Restore the database files as:" Table, Go to the [Restore As] column
Notice the string in the first row (for Data) and the string in the second row (for Images) are exactly the same. This will result in some errors.
Change the string in the first row to something else (like adding a date), for example
C:................\YourFileName.mdf
C:................\YourFileName20151124.mdf
Problem solved
Here's my full Script:
RESTORE DATABASE [Makhado_Indigents] FROM DISK = N'C:\IndiCheck\Makhado_Indigents.bak'
WITH FILE = 1, MOVE N'New_Indigents'
TO N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.INDICHECK\MSSQL\DATA\Makhado_Indigents.mdf',
MOVE N'New_Indigents_Images'
TO N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.INDICHECK\MSSQL\DATA\Makhado_Indigents1.mdf',
MOVE N'New_Indigents_log'
TO N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.INDICHECK\MSSQL\DATA\Makhado_Indigents.ldf',
MOVE N'New_Indigents_Docs'
TO N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.INDICHECK\MSSQL\DATA\Makhado_Indigents.New_Indigents_Docs',
NOUNLOAD, REPLACE, STATS = 10
GO
You may also need to Switch Filestreaming on by running the following script:
EXEC sp_configure filestream_access_level, 2 RECONFIGURE
Restart the server:
Start > All Programs > Microsoft SQL Server 2008 R2 > Configuration Tools > SQL Server Configuration Manager
Right Click on the Server and select Restart

Create/restore database from backup SQL Server Express

I don't have SQL Server Management Studio on my machine.
I have a database backup (SQL Server 2008 R2). There is SQL Server Express that installed with Visual studio 2010 ultimate installed on my machine.
How can I restore this back up on a database and attaching it to SQL Server Express?
Is there any solution wihout using SQL Managment Studio Express ?
Even with SQL Server Management Studio Express, you won't be able to restore this backup. The Express edition being installed with Visual Studio 2010 is version 2008 of SQL Server - your backup is one from a SQL Server 2008 R2 release - those backups cannot be restore onto a 2008 version.
You will need to download the SQL Server 2008 R2 Express version, and while you're at it - get the version with the Management Studio! Install this, and then you'll be able to restore your database backup.
If you really really want to restore your database without using Mgmt Studio - you can of course use a RESTORE statement in T-SQL and run this using the sqlcmd command line tool:
RESTORE DATABASE YourDatabaseName
FROM DISK = N'(path to your BAK file)'
WITH FILE = 1,
MOVE N'(your DB name)' TO N'(your SQL path)database.MDF',
MOVE N'(your DB name)_LOG' TO N'(your SQL path)database_LOG.LDF',
NOUNLOAD,
REPLACE,
STATS = 10
GO
(and of course, there's also a BACKUP command which you can use in a similar fashion - the MSDN Books Online are your friend for details about the syntax!!).
Late one but hopefully useful to others who are viewing this….
If the problem is restoring without management studio this can be easily solved by using sqlcmd as marc_s already pointed out.
However if the real problem is restoring 2008 R2 backup on SQL 2008 without using SSMS then only solution is using third party tools that can read backup and generate scripts for creating schema and inserting data.
Idea is to create empty database on SQL 2008 and use a third party tool to compare it to backup generated with 2008 R2.
I’ve used ApexSQL Diff and ApexSQL Data Diff with good success in my previous job but there are also good tools from Red Gate (SQL Compare) and Idera (Comparison toolset). If you look up online you’ll probably find a lot more….
Disclaimer: I’m not affiliated with any of the companies mentioned above…
Why don't you get SQL Managment Studio Express? It is free, and should allow you to administer local sql express instances.
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=c243a5ae-4bd1-4e3d-94b8-5a0f62bf7796
BACKUP DATABASE [AdventureWorks] TO
DISK = N'\\nas\Backup\L40\SQL2005\AdventureWorks_backup_200702120215.bak'
WITH NOFORMAT, NOINIT, NAME = N'AdventureWorks-Full Database Backup',
SKIP, NOREWIND, NOUNLOAD, STATS = 10
RESTORE DATABASE [AdventureWorksNew]
FROM DISK = N'\\nas\Backup\L40\SQL2005\AdventureWorks_backup_200702120215.bak'
WITH FILE = 1,
MOVE N'AdventureWorks_Data' TO N'C:\Data\MSSQL.1\MSSQL\Data\AdventureWorksNew_Data.mdf',
MOVE N'AdventureWorks_Log' TO N'C:\Data\MSSQL.1\MSSQL\Data\AdventureWorksNew_Log.ldf',
NOUNLOAD, STATS = 10
Following link provides similar solution as marc_s, and it goes even deeper. I was able to successfully create a new DB from Backup file with the solution provided in the link below.
http://codeonaboat.wordpress.com/2012/02/16/sql-server-2008-creating-a-database-from-a-bak-file/
The solution below is copied from above link:
In SSMS, open a query window in the master database of the database server. That’s where you will run the following queries.
See what the “LogicalName” of the database that has been backed up in the .bak file is
RESTORE FILELISTONLY FROM DISK =
'c:\DatabaseBackups\dev2012021601.bak'
This will give you the logical name of the database and its associated log file. Lets assume that the names are “dbname” and “dbname_log”
Now run the following restore command. Make sure that a database with the name you are trying to create doesn’t already exist (in the code sample below, dbForSocialMigration doesn’t exist).
RESTORE DATABASE dbForSocialMigration
FROM DISK = 'c:\DatabaseBackups\dev20120307.bak'
WITH
MOVE 'dbname' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\dbForSocialMigration.mdf',
MOVE 'dbname_log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\dbForSocialMigration_log.mdf'
C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA is the directory where SQL Express usually keeps its data files. You can find the directory your database server is using by selecting a database from it, right clicking and opening the properties dialog and selecting the “Files” option from the left.
That should work, and at that point you should be able to access the database “dbForSocialMigration” populated with all the tables and data from the .bak file.

Resources