Need to make a .bat file to stop and then restart a SQL Server database - sql

We have a Dexis dental xray installation that uses SQL Server 2005 as the database. In order to back up the data, I have to open SQL Server Configuration Manager, stop the database, and then run Backup Exec. When it finishes, I have to restart the database.
I need to be able to automate this in Backup Exec 16, so I figured I would create a batch file that runs before the backup to stop the database. I could then execute a second batch to restart.
Can anyone give me a Dos box command that will stop and then restart a SQL Server database?
Thanks.
I thought that backing up the MDF and LDF files only backed up the database, and would not back up the actual data. I also thought that you had to stop the database in order to be given access to the data.
Amazingly, Dexis tech support people have no white papers, no protocols, and no suggestions on how to back up the data.
What is the proper method for backing the entire thing up so that if the server melts down, we can easily recreate the database AND the data?

On the WIndows command prompt, just use the NET STOP command to stop the MSSQLSERVER service, and NET START to restart it again:
NET STOP MSSQLSERVER
.....
REM do your backup here
.....
NET START MSSQLSERVER
Update: however, copying around the SQL Server database files (.mdf and .ldf) to do a server backup is not the recommended way of doing this.
Instead, you should use SQL Server's own BACKUP DATABASE ... functionality to generate .bak files, and then include those .bak files in your file-based backup and skip the .mdf and .ldf files

I am totally agreed with #marc_s answer but have added few more things. We will require Admin permission for such action, so added that check. Here is my batch file -
#echo off
if not "%1"=="am_admin" (powershell start -verb runas '%0' am_admin & exit /b)
NET STOP MSSQL$SQL2017 /y
NET START MSSQL$SQL2017
timeout 5
NET STOP SQLAgent$SQL2017
NET START SQLAgent$SQL2017
timeout 5
NET STOP SQLBrowser
NET START SQLBrowser
Have tested that with Win 10, powershell is used for checking admin rights.

Related

Repair Suspected TFS database

i am using this T-SQL to repair my TFS suspected database
EXEC sp_resetstatus [TFS_Projects];
ALTER DATABASE [TFS_Projects] SET EMERGENCY
DBCC checkdb([TFS_Projects])
ALTER DATABASE [TFS_Projects] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
DBCC CheckDB ([TFS_Projects], REPAIR_ALLOW_DATA_LOSS)
ALTER DATABASE [TFS_Projects] SET MULTI_USER
but when i use this T-SQL i will get error
Database 'TFS_Projects' cannot be opened due to inaccessible files or insufficient memory or disk space.
how can i repair my SQL database?
i am using SQL Server 2012
UPDATE 1:
this error will Occurred in line :
DBCC checkdb([TFS_Projects])
UPDATE 2:
i have 20GB free on hard drive that my mdf and ldf on it
UPDATE 3:
i can not chek Autogrow becuase when i right click on db the error will appear
mdf and ldf is not readonly
and i am loged in by windows administartor, and loged in sql server by sa
1) If possible add more hard drive space either by removing of unnecessary files from hard drive or add new hard drive with larger size.
2) Check if the database is set to Autogrow on.
3) Check if the account which is trying to access the database has enough permission to perform operation.
4) Make sure that .mdf and .ldf file are not marked as read only on operating system file system level.
Found here: http://blog.sqlauthority.com/2007/08/02/sql-server-fix-error-945-database-cannot-be-opened-due-to-inaccessible-files-or-insufficient-memory-or-disk-space-see-the-sql-server-error-log-for-details/
i update my answer becuase old answer is dangerous and will damage TFS database!
this answer is from microsoft : http://msdn.microsoft.com/en-us/library/jj620932.aspx
To back up your databases
Launch TFSBackup.exe.
The TFSBackup.exe tool is in the Tools folder where you installed Team Foundation Server. The default location is C:\Program Files\Microsoft Team Foundation Server 12.0\Tools.
In Source SQL Server Instance, enter the name of the SQL Server instance that hosts the TFS databases you want to back up and choose Connect.
In Select databases to backup, choose the databases to back up.
Need help? List of TFS 2010 databases on MSDN; List of TFS 2012 databases on MSDN.
In Backup Databases to, enter the name of a network share that is configured with read/write access for Everyone, or accept the default location in the file system of the SQL Server you connected to in step 2.
Note Note
If you want to overwrite backups stored in this network location, you can choose Overwrite existing database backups at this location.
Choose Backup Now.
The Backup tool reports progress on each database being backed up.
Choose Close.
Restore your data
To restore your TFS data
Launch TFSRestore.exe.
The TFSRestore.exe tool is in the Tools folder where you installed Team Foundation Server. The default location is C:\Program Files\Microsoft Team Foundation Server 12.0\Tools.
In Target SQL Server Instance, enter the SQL Server instance you will use as the data tier and choose Connect.
Choose Add Share and enter the UNC path to the network share that is configured with read/write access to Everyone where you stored the backups of your TFS data. For example, \servername\sharename.
If the backup files are located on the file system of the server that is running TFSRestore.exe, you can use the drop down box to select a local drive.
Note Note
The service account for the instance of SQL Server you identified at the start of this procedure must have read access to this share.
In the left hand navigation pane, choose the network share or local disk you identified in the previous step.
The TFS Restore Tool displays the database backups stored on the file share.
Select the check boxes for the databases you want to restore to the SQL Server you identified at the start of this procedure.
Important note Important
For SharePoint, you must only restore the WSS_Content database. Do not restore the WSS_AdminContent or WSS_Config databases. You want the new SharePoint Foundation versions of these databases, not the ones from the previous version of SharePoint or from a SharePoint installation running on any other server.
Choose Overwrite the existing database(s) and then choose Restore.
The Database Restore Tool restores your data and displays progress reports.
Choose Close.
Probably your database is corrupt either due to an unexpected server restart or filesystem corruption. You can use CheckDB to check for issues & remove the suspect status. However, the best bet is to restore it from a working backup.
Some reasons for when this happens are
Database is corupted
database files are being "opened" or held by some process (operating system, other program(s)...)
Not enough disk space for SQL Server
Insufficient memory (RAM) for SQL Server
Unexpected SQL Server shutdown caused by power failure
How to repair a suspect database

How to create sql script to dump sql server table data?

I am new to sql scripting. I have a problem where I sometimes run a standalone mode that doesn't allow a connection from my database to my actual program. I am trying to automate a way to take the data out of my sql server database and push it to my program somehow. Just as a backup.
Is this possible?
Source: fmsinc.com/free/NewTips/SQL/SQLServerExpr..
Download and install the SQL Server Management Studio Express interface from the following URL (if you do not already have this utility installed on your server):
http://www.microsoft.com/downloads/details.aspx?FamilyID=c243a5ae-4bd1-4e3d-94b8-5a0f62bf7796&displaylang=en
Please note that an installation of SQL Server Express does not install this interface (at the time this article was created for the 2005 version). This is a separate download.
Open the SQL Server Management Studio Express interface.
Create a new backup device using the wizard (expand Server Objects => New Backup Device).
Right click on the new backup device and select the database that you wish to backup.
Select the backup type (most often this is “Full”).
Choose a name for the job. Insert a description if you would like.
Click the Add button to add a Device Destination (this is where you would like the backup .bak output file to be placed).
Click Ok. The backup device is now setup. Repeat steps 3-7 for each database that you wish to backup.
Create a batch file using the following syntax (this is used to execute the backup device).
A syntax example is below (remember to save this file with a “BAT” file extension):
===< Begin Code Batch Script >===
sqlcmd -S MYSERVER\OFFICESERVERS -E -Q "BACKUP DATABASE MASTER TO TEST"
===< End Code Batch Script >=====
..where “MYSERVER” is the name of the SQL Server machine.
..where “OFFICESERVERS” is the name of the SQL Server.
..where “Test” is the name of the backup job.
..where “MASTER” is the name of the database.
Finally, open the Microsoft Windows Scheduler and assign the batch file created above to a scheduled event. Set the event to run at the point you wish.
EDIT: As you asked if 2 peoples are working remotely - in that case one will be server or both will be clients. What you can do is to create backup file on Server & the get that backup file for client OR in other case define 2 different Jobs & set their starting points for each of them. A backup file will be created for each job that will be executed & get that from destination for each client.

Restore Database from URL (Azure storage) fails without further details

On a Windows Azure VM running Windows 2008 R2 and SQL 2012 Enterprise SP1 CU5, I'm trying to restore a backup stored in Azure as a page blob with the new functionality RESTORE DATABASE FROM URL.
So far I've done it several times with backups up to 60GB in size (uncompressed) and it works like a charm.
However, there is a particular backup 32GB in size that I can't restore. It fails with the following error message:
Msg 3013, Level 16, State 1, Line 2
RESTORE DATABASE is terminating abnormally.
No further information is provided as to why it fails. If I download the same backup from to the local hard drive I can restore it without problem. I tried executing
dbcc traceon(3004,3605,-1)
to get more info and I can see that the DB is restored successfully, then it zeroes in the log file and after that completes is when it fails.
There isn't any error message in the SQL logs, neither in Windows Event log.
There is plenty of free space on that hard drive.
VM and storage are in the same datacenter and I've followed all best practices in building the environment.
EDIT> I noticed the following lines in Event viewer AFTER the database is restored and BEFORE it starts restoring the LOG file (in other words, while the log file is being zeroed)
SQLVDI: Loc=CVDS::Close. Desc=Open devices!. ErrorCode=(0). Process=2900. Thread=1104. Client. Instance=MSSQLSERVER. VD=Global\https://url/stuff/xx.bak_SQLVDIMemoryName_0.
SQLVDI: Loc=SignalAbort. Desc=Client initiates abort. ErrorCode=(0). Process=2900. Thread=1104. Client. Instance=MSSQLSERVER. VD=Global\https://url/stuff/xx.bak_SQLVDIMemoryName_0.
SQLVDI: Loc=TriggerAbort. Desc=invoked. ErrorCode=(0). Process=1508. Thread=2008. Server. Instance=MSSQLSERVER. VD=Global\https://url/stuff/xx.bak_SQLVDIMemoryName_0.
Is it possible that the connection to Azure storage times out before the zeroing finishes and thus the RESTORE fails? If so, how do I change this timeout?
You may wish to try enabling instant file initialization (it solved the problem for me). To do this you need to grant the SQL service account the 'Perform volume maintenance tasks' permission in security policy.
For instructions, see:http://blogs.msdn.com/b/sql_pfe_blog/archive/2009/12/23/how-and-why-to-enable-instant-file-initialization.aspx
With thanks to this 'question' for providing the answer:https://stackoverflow.com/questions/20692592/restoring-large-database-backups-from-azure-blob-storage-to-sql-server-2012-in-a
For anyone having this issue i found a different workaround.
Rather than creating the backup Log file to store on Azure blob storage, i changed that part of the script generated before execution to store it to local disk.
I'm unsure as to why the log file is not successfully being created when SQL attempts to write it to the blob storage.
Here is a segment of the script in questiona fter my amendmants :-
USE [master]
BACKUP LOG [RealTime] TO DISK = N'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQL14\MSSQL\Backup\YourDb_LogBackup_2015-07-07_09-04-17.bak'
WITH NOFORMAT, NOINIT, NAME = N'YourDb_LogBackup_2015-07-07_09-04-17', NOSKIP, NOREWIND, NOUNLOAD, NORECOVERY , STATS = 5
Leave the rest of the script generated to RESTORE the database as is.

SQL Server Express unable to attach or delete mdf file

My database file Whist.mdf was attached to a SQL Server Express through Management Studio, but it stopped working in that sense that NHibernate in my asp.net solution fired some connection exceptions. I just detached it from Management Studio because I couldn't open the database in there either.
But when I try to reattach it I get this error:
Attach database failed for Server 'MyPCName\SQLECPRESS'. (Microsoft.SqlServer.Smo) Unable to open the physical file "C:\Program
Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\Whist.mdf".
Operating system error 32: "32(process cannot access the file because
it is being used by another process)". (Microsoft SQL Server, Error:
5120)
I have googled it but can't find a solution that works for me. E.g.:
http://www.byteblocks.com/post/2010/01/06/Unable-to-open-the-physical-file-Microsoft-SQL-Server.aspx
"Cannot open user default database. Login failed." after installing SQL Server Management Studio Express
There is something about User Instance but I cant figure out if it have anything to do with that:
http://blogs.msdn.com/b/sqlexpress/archive/2006/11/22/connecting-to-sql-express-user-instances-in-management-studio.aspx
I have tried to delete the mdf file in windows but I can't do that either:
The action can't be completed because the file is open in system
I have tried stopping the SQL Server process, closing explore and delete from cmd and rebooting...
Hope someone can help - I guess it is just a simple thing..
I think you are on the right track. The error messages you are getting indicate that some SQL Server process is keeping the database file open. And SQL Server is designed to only allow the database file to be open by a single SQL Server process at a time.
You are also probably right to suspect User Instance of SQL Server Express to be the guilty process here. User Instance is a special SQL Server process that doesn't run as a service and instead is started and owned by the application that tries to connect to it. In your case there are two User Instances that can be the problem, one owned by the ASP.NET application you mentioned and one owned by you and started by Visual Studio. If you are using IIS Express or you configured the IIS App Pool for the ASP.NET application to run as your account then we only have one User Instance to worry about.
My recommendation is that you don't use User Instances and don't try to connect directly to the database file. Go over your connection strings and remove User Instance=true from all of them. You want to remove AttachDBFilename=... property as well.
If the database file is added to any of your Visual Studio solutions remove it (just be careful not to delete the file itself). The last step is to remove any connections to the database file from your Data Connections node in the Server Explorer.
Then restart the machine to make sure any User Instances that were running in the background were shutdown. After the machine starts again you should be able to attach the database file back to your main SQL Server Express using SQL Server Management studio. Let's name the database Whist
To connect to your database use the following connection string:
Data Source=.\SQLExpress;Integrated Security=true;Initial Catalog=Whist
When you connect from the ASP.NET application, make sure that you have created an account in your SQL Server Express for the application.
Turned out to be an issue with Daemon tools for me as well associating the .mdf file as an image.
If you want to copy your .mdf and .ldf file from your database, you can set your database file to 'offline' first . Please follow this steps:
Open your SQL Server 2008(suppose you are using SQL Server 2008 ).
Select your Database that you want to copy then left click.
Go to Tasks -> Take Offline.
Right click.
Then you can copy this database file to any folders.

SQL Server 2005 Restore Hanging

I have a database showing up in SQL Enterprise Manager as "(Restoring...)"
If i do SP_WHO there is no restore process.
The disk and CPU activity on the server is very low
I think it is not restoring at all.
How can I get rid of this?
I've tried renaming the underlying MDF file, but even when I do "NET STOP MSSQLSERVER" it tells me the file is open.
I've tried using PROCEXP to find what process has the file open, but even the latest PROCEXP can't seem to do that on Windows Server 2003 R2 x64. The lower pane view is blank.
In the SQL Server log it says "the database is marked RESTORING and is in a state that does not allow recovery to be run"
Sql Server has two backup types:
Full backup, contains the entire database
Transaction log backup, contains only the changes since the last full backup
When restoring, Sql Server asks you if you want to restore additional logs after the full backup. If you choose this option, called WITH NORECOVERY, the database will be left in Restoring state. It will be waiting for more transaction logs to be restored.
You can force it out of Restoring mode with:
RESTORE DATABASE <DATABASE_NAME> WITH RECOVERY
If this command gives an error, detach the database, remove the MDF files, and start the restore from scratch. If it keeps failing, your backup file might be corrupted.
Here's a screenshot of the restore options, with the default selected. The second option will leave the database in Restoring state.
Image of the restore options http://img193.imageshack.us/img193/8366/captureu.png
P.S.1. Are you running the 64 bit version of process explorer? Verify that you see procexp64.exe in the task manager.
P.S.2. This is more like a question for serverfault.
WITH RECOVERY option is used by default when RESTORE DATABASE/RESTORE LOG commands is executed. If you're stuck in "restoring" process you can bring back a database to online state by executing:
RESTORE DATABASE YourDB WITH RECOVERY
GO
You can look for more options and some third party tools on this SO post https://stackoverflow.com/a/21192066/2808398
If you are trying to get rid of the lock on the file I would recommend getting Unlocker http://www.emptyloop.com/unlocker/
It'll give you an option to unlock the file, or kill the process that has locked the file. Run this on the mdf and ldf files.
Another option is to try to Detach the files from Enterprise Manager or Sql Management Studio and then reattach the db. You can try this before running unlocker to see if sql server will just release the mdf and ldf files.
CAUTION: If you kill the process you might lose data or the data might get corrupted so use this only if you are trying to get rid of it and you have a good and tested backup.