In SQL server user have to follow below steps to restore database from backup file.
right click on the Databases container within object explorer.
from context menu select Restore database.
Specify To Database as either a new or existing database.
Specify Source for restore as from device.
Select Backup media as File.
Click the Add button and browse to the location of the BAK file.
Is there any script/command to restore the same without doing the above methods?
Just before you click on the last OK button on SSMS Backup/Restore Wizard ... you can Click on the script drop down button and pick script to New Query Window (The script drop down is Next to the Help button and above the Source/Database Name) and it will generate the Exact command that SSMS will execute against the DB. So you can use that command from the Query window to do the same thing programatically in TSQL. Indeed you can even put that inside a Stored PRocedure if you want to execute the same command all the time like so:
CREATE PROCEDURE dbo.dbBackup AS
BEGIN
RESTORE DATABASE [MyDataBaseName] FROM DISK = N'C:\SQLData\MyDB.bak'
WITH FILE = 1, NOUNLOAD, STATS = 5
END
And to take it one more level you could assign that SP to a hotkey as explained over here : https://www.mssqltips.com/sqlservertip/1287/assign-shortcuts-to-commands-in-sql-server-management-studio/
To access the screen below, open a query window and select from the menu Tools -> Options and then under the Environment node select Keyboard --> Query Shortcuts this will allow you to assign a stored procedure to execute for the Hotkey combination that is best for you.
One thing to be care full about though is to make sure that this does not replace an existing DB because you could accidentally overwrite a good DB if the restore command includes that option
"Automate" is a very broad term in your question, but if C# is an option, you can use the SQLCommand Class to execute the Restore, as below
sqlCmd.CommandText = "RESTORE DATABASE [" + restoreDbName + "] FROM DISK =
N'" + backupFileName + "' WITH FILE = 1, MOVE '" + logicalNameMdf + "' TO '"
+ restorePathMdf + "', MOVE '" + logicalNameLdf + "' TO '" + restorePathLdf + "', "
+ " NOUNLOAD, REPLACE";
sqlCmd.ExecuteNonQuery();
Related
Been working on my first Entity Framework project. As part of the project I am going to be creating a number of SSRS reports. In order to connect to the database I need to have a Reports user that will only access to the specific database on the server. In the past i have always written a script to add Database users but I want to know is there a way that i can do this using Entity Framework instead?
Assuming your user already has a login defined at the SQL Server level (Security > Logins), you can call the following method from your DB initializer seed method to add the user to the database:
private void AddDbUser(MyDataContext myDB)
{
string accountDomainName = "AccountDomainName"; // replace with user's login domain
string accountLoginID = "AccountLoginID"; // replace with user's login ID
string sql =
"USE [MyDB]" +
"CREATE USER [MyNewUser] FOR LOGIN [" + accountDomainName + "\\" + accountLoginID + "]" +
"ALTER AUTHORIZATION ON SCHEMA::[db_datareader] TO [" + accountLoginID + "]" +
"ALTER AUTHORIZATION ON SCHEMA::[db_datawriter] TO [" + accountLoginID + "]" +
"EXEC sp_addrolemember N'db_datawriter', N'" + accountLoginID + "'" +
"EXEC sp_addrolemember N'db_datareader', N'" + accountLoginID + "'";
myDB.Database.ExecuteSqlCommand(sql);
}
The exact SQL needed is dependent on your configuration. To have SQL Server generate the SQL for your scenario, you could open the add user dialog in SSMS (Database > Users > New User...), fill out the fields, and click the "Script" button at the top instead of hitting OK at the bottom. Note that any "GO" lines will need to be removed from the generated script before pasting it into the method above.
You would need to tell EF to use the appropriate stored procedures to do so. You could also wrap these up in a sproc of your own that wraps the relevant commands. There is no native "CreateReportsUser" type method within EF that I know of.
Edit: I probably should have provided this reference to be a "complete" answer. Apologies.
Here's how you can do what I recommend: How to call Stored Procedure in Entity Framework 6 (Code-First)?
We attached the database PStorage to the server.
Then I tried to create the login & user using the following code:
Dim con As New SqlConnection
Dim query As SqlCommand
con.ConnectionString = "Server=(LocalHost);Data Source=LocalHost\SQLEXPRESS;Database=PSTORAGE;Integrated Security=TRUE"
con.Open()
query.CommandText = "IF NOT EXISTS(SELECT [LoginName] FROM MASTER.DBO.SYSLOGINS WHERE [Name]='UserCP') CREATE LOGIN UserCP WITH PASSWORD='CPPassword'"
query.ExecuteNonQuery()
query.Dispose()
query.CommandText = "IF NOT EXISTS(SELECT [Name] FROM SYS.DATABASE_PRINCIPALS WHERE [Name]='CPUser') CREATE USER CPUser FOR LOGIN UserCP"
query.ExecuteNonQuery() 'This line is throwing the error -> Login Failed for the User 'UserCP'.
query.Dispose()
The error we are getting after executing the second query is
Login failed for the user 'UserCP'
While attaching the database the same error occurs. Then we had to use sqlCmd.
In all the systems this method works fine. But in one of our customers system this problem occurs. What might be the reason?
After a lot of tries we could come to know that the folder was compressed [All the file names were in blue colour]. Since the database files were inside the compressed folder- none of the operations could be done on them perfectly.
Right click on the database folder, Press on Properties
Press on Advanced
Untick the Compress contents to save disk space
Save the changes made
I'm working on an app that is using a database that is encrypted by sqlcipher. The passwort for this encryption is stored by cacheword.
To make a backup of my database I used the following code:
// ggf. Datenbank öffnen
openGuard();
mDb.execSQL("ATTACH DATABASE '" + outFileName + "' AS backup KEY 'asdfghjkl';");
mDb.rawExecSQL("SELECT sqlcipher_export('backup');");
mDb.execSQL("DETACH DATABASE backup;");
The method openGuard() is used to check if the database is opend yet and if not do this.
I've checked the backup by using an empty key to make an unencrypted copy of my database. Then I can use it on adb shell and use sql-statements to get the wanted data.
My problem now for a long time is that I'm not able to use my backup to restore the database of my app. I tried this code:
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(backupFile, "asdfghjkl", null);
db.execSQL("ATTACH DATABASE '" + dbFile + "' AS encrypted KEY '" + mCacheWord.getEncryptionKey() + "';");
db.rawExecSQL("SELECT sqlcipher_export('encrypted')");
db.rawExecSQL("DETACH DATABASE encrypted;");
Alternatively I tried
db.execSQL("ATTACH DATABASE '" + dbFile + "' AS encrypted KEY '" + encodeRawKey(mCacheWord.getEncryptionKey()) + "';");
But in both cases I get the following error message:
10-30 00:56:42.845: I/Database(14407): sqlite returned: error code = 26, msg = statement aborts at 5: [ATTACH DATABASE '/data/data/.../databases/database.db' AS encrypted KEY '[B#42082da0';] file is encrypted or is not a database
10-30 00:56:42.845: E/Database(14407): Failure 26 (file is encrypted or is not a database) on 0x63bdedb0 when executing 'ATTACH DATABASE '/data/data/.../databases/database.db' AS encrypted KEY '[B#42082da0';'
Is there anyone how can help me with my problem?
Looks like you've gotten accidentally "hung up" trying to decrypt by supplying the key via the ATTACH DATABASE statement. Looking at Example 2: Decrypt a SQLCipher database to a Plaintext Database of the API, there's a comment that reads -- empty key will disable encryption. So, presumably your initial decryption code attempt should first execute the PRAGMA key = statement (to supply the key) and then the ATTACH DATABASE statement with empty key (to decrypt) something like this:
db.execSQL("PRAGMA key = '" + mCacheWord.getEncryptionKey() + "';");
db.execSQL("ATTACH DATABASE '" + dbFile + "' AS encrypted KEY '';");
db.rawExecSQL("SELECT sqlcipher_export('encrypted')");
db.rawExecSQL("DETACH DATABASE encrypted;");
Another brief example about this can be seen in this the SQLCipher Users mailing list discussion.
I believe the problem may have to do with the fact that you are using CacheWord, which manages the encryption key separately from SQLCipher. You should verify the format of the string returned from getEncryptionKey() and ensure that it matches the proper format for a raw key in SQLCIpher.
I have a job stored on a database, scheduled to run every day. But its sometimes necessary to want to execute this job at any given time to view up to date data (I'm using SQL Server Management Studio 2008).
The job itself simply takes data from a view which contains live data and puts it into a table which will then be used as a data source for an excel file. Executing the job drops and re-creates the table with fresh data.
In excel (2010), i wish to have a 'button' which which pressed will execute the job and then hitting refresh on the data tab in excel will then update the data on the sheet with the fresh data.
My question is: How do i execute this job from an excel macro?
Private Sub CmdRunJob_Click()
Dim con As Object
Set con = CreateObject("ADODB.Connection")
con.Open = "DRIVER={SQL Server};SERVER=YourServer;" & _
"USER=YourUser;PASSWORD=YourPassword;"
con.Execute "exec msdb.dbo.sp_start_job 'YourJob'"
End Sub
You create a SP that moves data from view to table.
Then modify the Job that it executes that SP by schedule.
Then in Excel Macro you can just use that SP to update the data.
Or see example how to run the Job from VBScript
You can use SQLDMO.SQLServer to execute your job.
We have an Access UI to Sql Server database. The user connects to many databases (containing the same tables with different data), can choose between them. We use this for versioning. We want to make him able to copy and delete databases right from Access UI. He should be able to copy at least to the same server, and ideally also to other server.
A Backup and restore is probably going to be your best bet. There is another way as well. But there will be some restrictions.
You can detach the DB you want to copy, make a copy of the files attach the old one, and attach the new one as a new DB. Your problem will be because you are using Access to connect to the DB, you will not be able to detach it because there is a connection to it, and all connections must be dropped before you can detach it.
Dropping the DB (delete it) will have the same problem. It won't drop unless you there is no connections on the DB.
This is my final solution:
Dim conn As New ADODB.Connection
conn.ConnectionString = "Provider=SQLOLEDB;Data Source=" dbServer & ";" _
& "User ID=" & user & ";Password=" & password
conn.Open
' backup
conn.Execute "BACKUP DATABASE [" & sourceDb & "] TO [backup device] WITH NOFORMAT, NOINIT, NAME = N'backup', SKIP, NOREWIND, NOUNLOAD, STATS = 10"
' restore
conn.Execute "RESTORE DATABASE [" & targetDb & "] FROM [abcosting temporary backup] WITH FILE = 1, NOUNLOAD, REPLACE, STATS = 10, " & mdf_move & ", " & ldf_move