Actually I'm developing a vb .net desktop app that needs to restore a database using a .bak How to do that? - sql

I'm getting this:
"Exclusive access could not be obtained because the database is in use.
RESTORE DATABASE is terminating abnormally."
First the message told me I must connect to master db to execute the restore but I change it and I got the message above.
The parametrized sql statement I'm using is:
cmd.CommandText = "RESTORE DATABASE aguasdelbosque " +
"FROM DISK = #archivo"

You first need to kick all users out of the database, take a look at Kill All Active Connections To A Database on how to do it

Another approach to restoring the database is using the SQL Server Management Objects library. To kill all processes, the Server class has the method KillAllProcesses or KillDatabase. The Database class has the methods SetOffline and SetOnline. To restore the database you would use the SqlRestore method of the Restore class. For more information or further reading try the links below.
http://www.sqldbatips.com/showarticle.asp?ID=40
http://social.msdn.microsoft.com/Forums/en/sqlsmoanddmo/thread/08416c9d-0e8d-4021-b5ea-b9dc634c03e8
http://social.msdn.microsoft.com/Forums/en-US/sqlexpress/thread/52638e68-5c88-49f1-9b76-6bfa2387da18
http://sqlblogcasts.com/blogs/seanprice/archive/2007/07/11/Killing-ProcessIDs-using-SMO.aspx
http://www.codeproject.com/KB/database/BackupRestoreWithSmo.aspx

Related

SubmitChanges() updates database in bin folder

My code and the Linq to sql function SubmitChanges are working, but when using a local database a copy of the database in the bin folder is updated and not the primary database. So the changes aren't shown on a new query. If I re-connect the database but don't load it as local same problem - the primary database isn't updated, but now I can't figure out which one is (tks to this question).
What setting for a local db or how do I use a non-local database to show changes on a new query of the database?
Dim DATA As New lnqPolarisDataContext
Dim newBOOK As New BOOK()
newBOOK.ID = 14
newBOOK.LEG = 11
newBOOK.P_C = "C"
newBOOK.STRATEGY = "STRADDLE"
newBOOK.STRIKE = 999
newBOOK.CONTRACT = "XXX"
DATA.BOOKs.InsertOnSubmit(newBOOK)
DATA.SubmitChanges()
... new query doesn't show these changes
maybe this is the best method?
The real solution in my opinion would be to put your database on the server where it belongs - after all, SQL Server is a server-based solution, not a file-based "database".....
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. YourDatabase)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=YourDatabase;Integrated Security=True
and everything else is exactly the same as before...
Also see Aaron Bertrand's excellent blog post Bad habits to kick: using AttachDbFileName for more background info.

Can you backup a local SQL Server database with a "BACKUP DATABASE" script?

The problem is...
I have a small windows form application running .NET 4.0 Framework and a local SQL Server 2012 database file to store the data (.MDF file). This database is not being used in relation with SQL Server and is being managed through the Visual Studio Server Explorer.
The task that I have is that I want to do backups on this database through the software itself or a service. I have looked around the internet and I have found that there is a script BACKUP DATABASE [DatabaseName]. I have tried running this against my local database and it says the database name is not recognized.
This is the code I have tried.
Private Sub btnBackup_Click(sender As Object, e As EventArgs) Handles btnBackup.Click
Dim FileName As String = Now.ToString("ddMMyyyy_HHmm") & ".bak"
sfdBackupDB.InitialDirectory = txtBackupFolder.Text
sfdBackupDB.FileName = FileName
If sfdBackupDB.ShowDialog() <> Windows.Forms.DialogResult.Cancel Then
If Not File.Exists(sfdBackupDB.FileName) Then
SQLExecute("BACKUP DATABASE [ExampleDB] TO DISK = '" & sfdBackupDB.FileName & "' WITH FORMAT")
End If
End If
End Sub
sfdBackupDB is a save file dialog
SQLExecute is my own method to run a simple script but is literally just an SQL command call.
The error that I get from this goes:
Database 'ExampleDB' does not exist. Make sure that the name is entered correctly. BACKUP DATABASE is terminating abnormally.
There should be nothing wrong with the SQL Server connection that I am using as all other queries through the application are working so it can see the database is connecting to. Just in case it is important, the connection string is below:
Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database\ExampleDB.mdf;Integrated Security=True
I have also found another method using SMO objects but I get pretty much the same outcome.
So my main questions are:
Is this type of backup possible with this type of database
Are there any better methods of doing it
Forgive my lack of knowledge but I have not had much experience with this type of local database as I have only really worked on SQL Server databases in SQL Server Management Studio.

Sql: export database using TSQL

I have database connection to database DB1. The only thing I could do - execute any t-sql statements including using stored procedures. I want to export the specific table (or even the specific rows of specific table) to my local database. As you can read abve, DBs are on diffrent servers meaning no direct connection is possible. Therefore question: Is it possible to write query that returns the other query to execute on local server and get data? Also note, that table contains BLOBs. Thanks.
If you have SQL Server Management Studio, you can use the data import function on your local database to get the data. It works as long as you have Read/Select access on the tables you are trying to copy.
If you have Visual Studio you can use the database tools in there to move data between two servers as long as you can connect to both from your workstation.
Needs Ultimate or Premium though:
http://msdn.microsoft.com/en-us/library/dd193261.aspx
RedGate has some usefull tools too:
http://www.red-gate.com/products/sql-development/sql-compare/features
Maybe you should ask at https://dba.stackexchange.com/ instead.
If you can login to the remote db (where you can only issue t-sql), you may create linked server on your local server to the remote and use it later directly in queries, like:
select * from [LinkedServerName].[DatabaseName].[SchemaName].[TableName]

Restoring a database using vb.net

Can anyone help me how to restore a database from vb.net,I tried to restore using stored procedure by taking retore template script from sql server2005. but there is error "the database is already in use please use a master database.."
I assume you used the same connection string you usually use to connect to the database you are actually restoring.
From you error message, I'd say you should create your connection to the server with a different InitialCatalog parameter (the error message indicates you should use "master").
The other option is to stick a "USE master" at the beginning of the script. Here is a small description of the USE statement.
From the error it doesn't look like there is an actual VB.net programmatic error.
It seems like the problem lies on the database restoration stored procedure.
Before restoring database, make sure that
• Your connection is not using the database you are restoring - That is one of the possible reasons for that error, "the database is already in use please use a master database.."
• Other connections to the target database should be closed off - Close all connection to it.
Denis Troller has mentioned "USE master" and make sure that your script has that statement as the very "first" statement in your restore batch script.
I just wrote this in my project so I thought I'd share my method.
I'm calling the backup and restore by firing the SQL at the server using an SqlCommand.CommandText and setting the SqlParameters for database and filename as follows:
Simple backup:
BACKUP DATABASE #dbName
TO DISK=#fileName
WITH FORMAT
Then restore it using :
USE master
RESTORE DATABASE #dbName
FROM DISK = #fileName
There are plethora of options on the BACKUP and RESTORE commands but I just wanted a quick sledge-hammer approach and this works nicely.
Thanks to Denis for the 'USE master' tip, which just fixed my 'in use' error!

SQL 2005 Linked Server Query Periodically Failing

We have a database running on SQL 2005. One of the store procedure looks up a user's email address from Active Directory using a linked server. The call to the linked server occurs in a database function.
I'm able to call is successfully from my Asp.Net application the first time, but periodically after that, it fails with the following error:
{"The requested operation could not be performed because OLE DB provider \"ADsDSOObject\" for linked server \"ADSI\" does not support the required transaction interface."}
It appears that the amount of time between calling the function affects whether the linked server query will work correctly. I am not using any transactions. When I try calling the function in a quick make-shift SQL script, it runs fine everytime (even when tested in quick succession).
Is there some sort of transaction being left open that naturally dies if I don't try calling the procedure again? I'm at a loss here.
Here is the simple call in the store procedure:
DECLARE #email varchar(50)
SELECT #email = LEFT(mail, 50)
FROM OPENQUERY (
ADSI,
'SELECT mail, sAMAccountName FROM ''LDAP://DC=Katz,DC=COM'' WHERE objectCategory = ''Person'' AND objectClass = ''User'''
)
WHERE sAMAccountName = CAST(#LoginName AS varchar(35))
RETURN #email
I've worked with SQL Server linkservers often, though rarely LDAP queries... but I got curious and read the Microsoft support page linked to in Ric Tokyo's previous post. Towards the bottom it reads:
It is typical for a directory server
to enforce a server limitation on the
number of objects that will be
returned for a given query. This is to
prevent denial-of-service attacks and
network overloading. To properly query
the directory server, large queries
should be broken up into many smaller
ones. One way to do this is through a
process called paging. While paging is
available through ADSI's OLEDB
provider, there is currently no way
available to perform it from a SQL
distributed query. This means that the
total number of objects that can be
returned for a query is the server
limit. In the Windows 2000 Active
Directory, the default server limit is
1,000 objects.
I'm thinking that the reason it fails on you (or not) depending on whether call it from the app or from a "quick make-shift sql script" (as you put it) might be related to the security context under which the operation is executing. Depending on how the link server connection was set up, the operation could be being executed under a variety of possible credentials depending on how you initiate the query.
I don't know, but that's my best guess. I'd look at the linkserver configuration, in particular the linkserver settings for what set of credentials are used as the security context under which operations executed across the linkserver run.
Rather then query Active Directory through a linked server, you might be better off caching your AD data into a SQL database and then querying that instead. You could use Integration Services by creating a OLE DB connection using "OLE DB PRovider for Microsoft Directory Services" and having a DataReader source with a query like:
SELECT physicalDeliveryOfficeName, department, company, title, displayName, SN,
givenName, sAMAccountName, manager, mail, telephoneNumber, mobile
FROM 'LDAP://DC=SOMECO,DC=COM'
WHERE objectClass='User' and objectCategory = 'Person'
order by mail
Using this method you will still run into the 1000 row limit for results from an AD query (note it is NOT advisable to try and increase this limit in AD, it is there to prevent the domain controller from becoming overloaded). Sometimes its possible to use a combination of queries to return the full data set, e.g. names A - L and M - Z
Alternatively you could use the CSVDE command line utility in Windows Server to export your directory information to a CSV file and then import it into a SQL database (see http://computerperformance.co.uk/Logon/Logon_CSVDE_Export.htm for more info on exporting AD data with CSVDE).
please read the support page from Microsoft
I suspect that it might be the cached query plan due to your statement that "When I try calling the function in a quick make-shift SQL script, it runs fine everytime (even when tested in quick succession)."
Could you try executing your stored procedure like so:
EXEC usp_MyProcedure WITH RECOMPILE
This question appears in the top of the first google page when search for the error string but has not valid answer.
This error happens intermitently when isolation level is not specified on .NET code nor in Store Procedure.
This error also happens in SQL Server 2008.
The fix is force SET TRANSACTION ISOLATION LEVEL READ (UN)COMMITTED because a isolation level any higher is not supported by Active Directory and SQL Server is trying to use SERIALIZABLE.
Now, as this error is intermitent. Why is ADO.NET or SQLServer switching its default isolation to SERIALIZABLE sometimes and sometimes not? What triggers this switching?