How to attach a SQL Server database from the command line - sql-server

Is it possible to enter a command line command (like in a batch file) to attach a detached database to SQL Server, in stead of opening the management studio and doing it in there?

you need to use: sqlcmd Utility
The sqlcmd utility lets you enter
Transact-SQL statements, system
procedures, and script files at the
command prompt, in Query Editor in
SQLCMD mode, in a Windows script file
or in an operating system (Cmd.exe)
job step of a SQL Server Agent job.
This utility uses OLE DB to execute
Transact-SQL batches.
Then use CREATE DATABASE (Transact-SQL) to do the attach and sp_detach_db (Transact-SQL) to do the detach. The sp_attach_db (Transact-SQL) is going to be removed in a future version of Microsoft SQL Server.

If you need to specify the log file name: USE master; GO; CREATE DATABASE DBNAME ON ( FILENAME = 'C:\DBFILE.mdf') LOG ON ( FILENAME = 'C:\DBLOGFILE_log.ldf') FOR ATTACH; GO; And to detach: USE master; GO; EXEC sp_detach_db 'DBNAME', 'true'; GO;

Small gotcha, it won't tell you what is wrong when using sqlcmd and your mdf/ldf files are marked read-only. Make sure they are read-write.

Related

Meaning of :out in sql

I have a sql file that I do not understand.
What does :out in the below code means?
This is not usual sql code, where can I learn about this script command?
Thanks!
USE [DATABASE_A]
GO
:out D:\xxx\xxxxxx.csv
exec sp_xxxx
go
It is a sqlcmd script:
By using the Database Engine Query Editor in SQL Server Management Studio you can write and edit queries as SQLCMD scripts. You use SQLCMD scripts when you have to process Windows System commands and Transact-SQL statements in the same script.
:out <filename>|stderr|stdout
The following example uses a sqlcmd statement to create an output file called testoutput.txt, executes two Transact-SQL SELECT
:out C:\testoutput.txt
SELECT ##VERSION As 'Server Version'
--- ...
It looks like a command that will be processed by SQLServer Management Studio to save the query results to the named file. It's not a part of the SQL standard, it's particular not only to SQLServer but specifically the SSMS query tool. You couldn't write this in another SQLServer query tool and guarantee it would work

How to run a Microsoft SQL Server Agent Job from VBScript

I have an ERP system that allows me to attach VBScript to a button on a customized window. I would like to be able to run this script so that it fires off a SQL Server Agent Job on the server (SQL Server 2008). I've been looking in to this for a couple hours now and the closest thing I could see was a short script which seems to use a depreciated command (SQL.DMO). Here's the code I swiped from the web:
On Error Goto 0: Main()
Sub Main()
Set objSQL = CreateObject("SQLDMO.SQLServer")
' Leave as trusted connection
objSQL.LoginSecure = True
' Change to match the name of your SQL server
objSQL.Connect "Server Name"
Set objJob = objSQL.JobServer
For each job in objJob.Jobs
if instr(1,job.Name,"Job Name") > 0 then
msgbox job.Name
job.Start
msgbox "Job Started"
end if
Next
End Sub
The resulting error is:
Line: 3
Char: 3
Error: ActiveX component can't create object: 'SQLDMO.SQLServer'
Code: 800A01AD
Source: Microsoft VBScript runtime error
Use sqlcmd and execute sp_start_job command:
Set oShell = CreateObject ("WScript.Shell")
oShell.run "sqlcmd -S localhost -E -Q ""EXECUTE msdb.dbo.sp_start_job N'My Job Name'""
sqlcmd should exist on the SQL Server.
Note:
This is a potential a security risk. As per documentation, by default, only members of sysadmin role can execute sp_start_job. You will need your VBScript to run under security context of a user that has sysadmin privileges in the SQL Server (which is not good).
Use Task Scheduler and a trigger file
Rather than starting the SQL Agent Job directly, create a Scheduled Task on the SQL Server that would:
be scheduled to run every 10 minutes
execute a cmd script, which would:
check for existence of a trigger file in a specified location
if file is found, would start the SQL Agent Job using sqlcmd, and delete the trigger file thereafter
The VBScript triggered by the ERP system should simply place an empty correctly named trigger file in the specified location.
Use a stored procedure to control what is being started
To further reduce attack vectors, you can create your own wrapper stored procedure in SQL Server that would start the required SQL Agent Job.
Create a server Login:
USE [master]
GO
CREATE LOGIN [erp_trigger_user] WITH PASSWORD=N'pwd', DEFAULT_DATABASE=[msdb], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF
GO
Create a database user:
USE [msdb]
GO
CREATE USER [erp_trigger_user] FOR LOGIN [erp_trigger_user] WITH DEFAULT_SCHEMA=[dbo]
GO
Create a stored procedure that will start your required SQL Server Agent Job:
Note: the stored procedure will execute as dbo user, which has permission to execute msdb.dbo.sp_start_job.
CREATE PROCEDURE dbo.sp_StartERPJob
WITH EXECUTE AS 'dbo'
AS
BEGIN
EXECUTE msdb.dbo.sp_start_job N'My Job Name'
END
Grant the user permissions to execute the stored procedure:
GO
GRANT EXECUTE ON [dbo].[sp_StartERPJob] TO [erp_trigger_user]
GO
Update your Scheduled Task to execute a Windows batch file that looks something like this:
if exist trigger_file.txt (
sqlcmd -S localhost -E -Q -U erp_trigger_user -P pwd "EXECUTE msdb.dbo.sp_StartERPJob"
del trigger_file.txt
) else (
rem file doesn't exist
)

Restoring database - Cannot access file because it is in use by another process

I have a backup of a database from another SQL Server 2005 machine. I'm attempting to restore it to my SQL Server 2008 instance.
I have created a new database for the restore to go in to, but when attempting the restore with the following (generated by ssms):
RESTORE DATABASE [WendyUAT]
FROM DISK = N'D:\wanda20130503.bak'
WITH FILE = 1,
MOVE N'Wendy' TO N'D:\databases\\WendyUAT.mdf',
MOVE N'Wendy_log' TO N'D:\databases\\WendyUAT.ldf',
MOVE N'sysft_WendyFti' TO N'D:\databases\\WendyUAT.WendyFti',
NOUNLOAD, REPLACE, STATS = 10
I get the following error:
System.Data.SqlClient.SqlError: The operating system returned the error '32 (The process cannot access the file because it is being used by another process.)' while attempting 'RestoreContainer::ValidateTargetForCreation' on 'D:\databases\WendyUAT.mdf'.
As far as I can tell (using Process Explorer etc) nothing else is using the file. I've disabled real-time protection in windows defender. I just cannot understand why SQL Server thinks the file is in use as windows explorer lets me delete it with no problems so Windows doesn't seem to think it's in use.
Any help would be gratefully received.
How are you connecting to your SQL Server in your application before running this backup? What database are you connecting to?
You cannot connect to the WendyUAT database and use it when you want to restore it - you'll have to explicitly use some other database, e.g. master, before running your SMO restore code
All my T-SQL restore scripts will always include:
USE [master]
GO
RESTORE DATABASE [WendyUAT] ......
So if you run this backup from your app, make sure you explicitly connect to e.g. master before running this T-SQL restore script
Update:
Is this something you did on purpose, or might it just be a typo??
MOVE N'Wendy' TO N'D:\databases\\WendyUAT.mdf',
* **
* *
* * two backslashes here -why???
* only one backslash here...
Does it work if you use single backslashes only??
RESTORE DATABASE [WendyUAT]
FROM DISK = N'D:\wanda20130503.bak'
WITH FILE = 1,
MOVE N'Wendy' TO N'D:\databases\WendyUAT.mdf',
MOVE N'Wendy_log' TO N'D:\databases\WendyUAT.ldf',
MOVE N'sysft_WendyFti' TO N'D:\databases\WendyUAT.WendyFti',
NOUNLOAD, REPLACE, STATS = 10
Try following script before restore
alter database DB_NAME set offline with rollback immediate;
and this script after restore to enable multi user
alter database DB_NAME set online with rollback immediate;
In my case I had installed two instances of SQL Server (2008 R2 and 2012). I had to stop one SQL Server service (2008 R2) from my two available SQL instances. This helped me to resolve this issue and I could restore my database.
I have the same issue.
What I did is that I just rename the Destination database to different name, then the restoration executed successfully. After the restoration, I just rename it to my desired database name.

How to remove a requested Backup file (.bak)?

I'm using SQL server 2005 and above and I wondering if there is a way to remove a specific backup file from the default SQL backups folder...
I can find that backups folder by using the query below:
EXEC master.dbo.xp_instance_regread
N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer',N'BackupDirectory'
The only way that I found was using the master.dbo.xp_delete_file operation, but the problem is that its cannot remove only one file (the requested one).
Any idea?
You might use xp_cmdshell to spawn a Windows command shell and execute a given string, as in:
xp_cmdshell 'del "E:\Database Backups\Some Database Backup.bak"'
Combined with your code to determine the default backup folder, you could construct the appropriate string to delete a specific file.
Note that xp_cmdshell is locked down by default for security reasons (obviously, running any arbitrary command string would be bad).

howt to use .MDF file

work on SQL Server 2000.i have CustomerDetails_Data.MDF file .from this file i want to take all information on my database .How to do?
You will need to attach the .mdf data file to a database in SQL Server. Then you can simply query the information.
If you just have an .mdf file (and no log file .ldf), follow these steps to create a Database from your lone .mdf file:
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 your requirement)
Execute sp_resetstatus <dbname>
Restart SQL server and see the database is online.
You need to attach the .mdf data file to SQL Server, and SQL server will automatically generate a new LOG file, after that you can pass any query to the database...
What format do you want to extract the information to? You could write sql scripts against it, or use bulk copy.

Resources