How do i backup one specific database from my database server - sql

Hi i want to backup one database of my database server using a bat and a sql file.
sqlcmd -S HEIST-BERG-SL\SQLEXPRESS -E -Q "C:\SALTO\Automatic Backups\scripts\backupDB.sql"
PAUSE
currently i'm missing something in this code to get my specific database called "Salto_Test" when i run the code above i backup all of my databases on the server and thats not what i want.
SQL
declare #datstr as varchar(100)=''
declare #currdate as datetime=getdate()
set #datstr=cast(DATEPART(YYYY,#currDate) as varchar(5))+right('00'+cast(DATEPART(MM,#currDate)as varchar(5)),2)+right('00'+cast(DATEPART(DD,#currDate)as varchar(5)),2)+right('00'+cast(DATEPART(HH,#currDate)as varchar(5)),2)+right('00'+cast(DATEPART(MINUTE,#currDate) as varchar(5)),2)
declare #path as varchar(500)='C:\SALTO\Automatic Backups\Salto_Test_db_' + #datstr +'.BAK'
backup database Salto_Test to disk= #path

If Database name is known then why go for the while loop and query string you can directly write query, Replace your SQL File code by below.
declare #datstr as varchar(100)=''
declare #currdate as datetime=getdate()
set #datstr=cast(DATEPART(YYYY,#currDate) as varchar(5))+right('00'+cast(DATEPART(MM,#currDate)as varchar(5)),2)+right('00'+cast(DATEPART(DD,#currDate)as varchar(5)),2)+right('00'+cast(DATEPART(HH,#currDate)as varchar(5)),2)+right('00'+cast(DATEPART(MINUTE,#currDate) as varchar(5)),2)
declare #path as varchar(500)='C:\SALTO\Automatic Backups\Salto_Test_db_' + #datstr +'.BAK'
backup database Salto_Test to disk= #path

Related

Using xp_cmpshell with variable in SQL Server

I want to use xp_cmdshell to ping servers. I created a procedure but I have a little problem, I need to select the server IP from table that is already created.
I created a cursor to get the server IP from the table but I don't know how to use the #ip varchar variable with ping command.
This syntax didn't work:
execute xp_cmdshell 'ping #ip'
You cannot reference parameters directly within xp_cmdshell, so you have to concatenate the value when creating the command. I recommend reading: https://msdn.microsoft.com/en-us/library/ms175046.aspx
In your example, you would do something like:
DECLARE #cmd nvarchar(4000);
SET #cmd = 'ping ' + #ip;
EXEC xp_cmdshell #cmd;

Combining a SQL database backup script/query with powershell

I am trying to combine this SQL backup script/query that I have with my power shell script and I'm not sure how to convert it as I don't know much about SQL only Powershell. I have been trying to use invoke-sqlcmd before every line in the script, but I don't think that's how you do it. I don't fully understand the syntax of invoke-sqlcmdMicrsoft was not helpful. This is the SQL database backup script I need to use:
DECLARE #name VARCHAR(50) -- database name
DECLARE #path VARCHAR(256) -- path for backup files
DECLARE #fileName VARCHAR(256) -- filename for backup
DECLARE #fileDate VARCHAR(20) -- used for file name
-- specify database backup directory
SET #path = 'F:\Backups\'
-- specify filename format
SELECT #fileDate = CONVERT(VARCHAR(20),GETDATE(),112)
DECLARE db_cursor CURSOR FOR
SELECT name
FROM master.dbo.sysdatabases
WHERE name IN ('dbname','dbname','dbname','dbname','dbname','dbname') -- exclude these databases
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO #name
WHILE ##FETCH_STATUS = 0
BEGIN
SET #fileName = #path + #name + '_' + #fileDate + '.BAK'
BACKUP DATABASE #name TO DISK = #fileName
WITH COMPRESSION
FETCH NEXT FROM db_cursor INTO #name
END
CLOSE db_cursor
DEALLOCATE db_cursor
Is it correct to just add invoke-sqlcmd in the front of every line of sql query? Also whatever solution there is to this needs to be compatible with Windows Server 2008 and up. I thought it might be as easy as just putting the whole script in quotes with invoke-sqlcmd, but I doubt it. Whenever I google this the answers are way too complex and don't really explain exactly how the SQL ties into Powershell. They just kind of assume you know. The only field in this script that needs to change is the path when you run it on SQL studio.
Sqlcmd is designed to be replacement for sqlcmd command-line tool.
Much of what you can do with sqlcmd can also be done using
Invoke-Sqlcmd.
Therefore you will execute your commands in one go. Either using external file or multi-line SQL string. See below for examples.
External File Example
Save your sql backup script to another file like backupDaily.sql. After that use following syntax.
Invoke-Sqlcmd -InputFile "C:\backupScripts\backupDaily.sql" | Out-File -filePath "C:\backupScripts\backupDailyCmd.rpt"
Command is taken from Microsoft documentation.
The good thing is you can try this sql file in Sql Server Management Studio to see if it works.
Multi-line SQL String Example
$SQL_QUERY = #"
YOUR QUERY HERE.
"#
Invoke-Sqlcmd -Query $SQL_QUERY -ServerInstance "MyComputer\MyInstance"
You may easily use string substitution here.
$name = 'atilla'
$SQL_QUERY = #"
SELECT * FROM Employees WHERE NAME LIKE $($name)
"#
Invoke-Sqlcmd -Query $SQL_QUERY -ServerInstance "MyComputer\MyInstance"
I wouldn't use powershell for doing a backup.
I would recommend using a SQL stored procedure to schedule a job.
USE msdb ;
GO
-- creates a schedule named NightlyJobs.
-- Jobs that use this schedule execute every day when the time on the server is 01:00.
EXEC sp_add_schedule
#schedule_name = N'NightlyJobs' ,
#freq_type = 4,
#freq_interval = 1,
#active_start_time = 010000 ;
GO
-- attaches the schedule to the job BackupDatabase
EXEC sp_attach_schedule
#job_name = N'BackupDatabase',
#schedule_name = N'NightlyJobs' ;
GO
Hopefully this link will help.
https://msdn.microsoft.com/en-GB/library/ms191439.aspx
You can use the sqlcmd to backup a database.
for the default instance
SqlCmd -E -S MyServer –Q “BACKUP DATABASE [MyDB] TO DISK=’D:BackupsMyDB.bak'”
for a named instance
SqlCmd -E -S MyServerMyInstance –Q “BACKUP DATABASE [MyDB] TO DISK=’D:BackupsMyDB.bak'”

xp_cmdshell Native Error 208, BCP in SQL Server 2008 R2

I've been trying to work on taking the result of a large and multiply-joined SELECT statement, and email the query result as a CVS file.
I have the query correct and the emailing down, but I'm having trouble automating the export of the result as a CVS file. From what I've been reading, the best bet for auto-exporting query results is a tool called "BCP".
I attempted to use BCP like this in Management Studio:
USE FootPrint;
DECLARE #sql VARCHAR(2048);
DECLARE #dir VARCHAR(50);
SET #dir = 'C:\Users\bailey\Desktop';
SET #sql = 'bcp "SELECT TOP 10 * FROM datex_footprint.Shipments" queryout "' + #dir + '" -c -t, -T';
EXEC master..xp_cmdshell #sql;
FootPrint is the name of a specific database, and datex_footprint a schema.
(This is not the real query, just a test one).
When I run this, the error I get is:
"SQLState=S0002, NativeError = 208"
"Error = [Microsoft][SQL Server Native Client 10.0][SQL Server] Invalid object name 'datex_footprint.Shipments'."
I am 100% positive that datex_footprint.Shipments is the correct schema\table access for the data I'm trying to test on.
Does anyone see what I'm missing or doing wrong in trying to export this result to a CSV file? Specifically, though, I'm trying to automate this process. I know how to export results into a CSV file, but I want to do it in T-SQL so I can automate the generation of the file by time of day.
Any help would be appreciated!
[SOLVED]
I figured out what I was doing wrong. I was not identifying the view in complete form. I was using "schema.Table/View", instead of "database.schema.table/view".
Also, I added a "-S" + ##SERVERNAME flag -- this tells the BCP utility to use the server SQL Server is currently connected to for the query.
The correct code to generate a CSV file of a SELECT-query's results in T-SQL, SQL Server 2008 is:
DECLARE #sql VARCHAR(8000);
SELECT #sql = 'bcp "SELECT * FROM FootPrint.datex_footprint.Shipments" queryout "C:\Users\bailey\Desktop\FlatTables\YamotoShipping.csv" -c -t, -T -S' + ##SERVERNAME;
exec master..xp_cmdshell #sql;
So once I added "FootPrint." to identify the database, it worked.
NOTE: I'm running SQL Server 2008 R2.
I have got same error but I have resolved it in a different way.
I have added the default database to my ID then BCP started looking the tables in my default database and processed the files.
After searching and reading the documentation of bcp, what I found was that when we have copy the data we should be using GLobal temp table i.e. ## instead of #.. because in tempdb it will collide and wont allow to copy the data to the destination file.
Example:
DECLARE #OutputFilePath nvarchar(max); SET #OutputFilePath = 'C:\OutputData'
DECLARE #ExportSQL nvarchar(max); SET #ExportSQL = N'EXEC xp_cmdshell ''bcp
"SELECT * FROM LW_DFS_DIT.dbo.##Mytemptable " queryout "' + #OutputFilePath +
'\OutputData.txt" -T -c -t '''
EXEC(#ExportSQL)
Hope this would help

xp_cmdshell copy command seldom fails

I am running SQL Server 2005 on Windows Server 2003 machine.
I have a requirement to accumulate small text files into a bigger one.
So I use
exec xp_cmdshell #sql
where #sql=
'copy /b'+#sourcePath+#sourceFile+' '+#destinationPath+#NewFileName
Both the source and destination paths are on a separate server.
Seldom this process fails and I don't find anything else in the event or SQL Server logs.
The Surface Area Config for xp_cmdshell is also enabled.
Please help.....
I just tested this on my sql server 2005 and EXEC dbo.xp_cmdshell always returns output (even in the case of a bogus command) in the form of a table. For C#, if you call this code with ExecuteNonQuery, then call it with ExecuteReader and read the output. Alternatively, you could dump the output in a table so that you can look at it later at your leisure. Create a table like this :
CREATE TABLE [dbo].[xp_cmdShellOutput](
[errorMsg] [nvarchar](max) NULL
)
and then use this code :
DECLARE #sql AS VARCHAR(600)
SELECT #sql = '<your command>'
INSERT dbo.xp_cmdShellOutput(errorMsg)
EXEC dbo.xp_cmdshell #sql

Which user account is running SQLCMD in T-SQL Script without -U and -P option?

I am using sqlcmd in a T-SQl script to write a text file to a network location. However SQLCMD is failing to write to that location due to access permission to the network folder. SP is being run under my user account which has access to the network folder.
Could you please help me under which account sqlcmd will run if I do not specify -U and -P option in TSQL Script?
Use this to find the user name:
PRINT Suser_Sname();
If you don't provide credentials with -u/-p it will try to use windows authentication; i.e the windows account of whomever is running it.
I often just use Process Monitor to look at what account is being used and what the permission error is.
You say you are using SQLCMD in a T-SQL script, don't you mean you are using SQLCMD to run a T-SQL script? How is your script writing a text file? Does it work in SQL Manager? My guess is that the user account SQL Server is running under doesn't have access to that location.
If you call an SQL script via xp_cmdshell without User and Password parameters it will run in the environment of the mssqlserver service, which is very much restricted, and without changing security parameters you will get mostly an 'Access is denied' message instead of the results of the script.
To avoid this security conflict situation I use the following trick in my stored procedure create_sql_proc. I read the text of the script file, and wrap it in a procedure by adding a head and a foot to it. Now I have a script creating a stored procedure from the SQL-file called #procname.
If you let now run this stored procedure by EXEC #procname, it will run in your security environment, and delivers the result you would get by running it from a command prompt:
CREATE PROCEDURE create_sql_proc(#procName sysname, #sqlfile sysname) AS
BEGIN
DECLARE #crlf nvarchar(2) = char(10)+char(13)
DECLARE #scriptText nvarchar(max)
DECLARE #cmd nvarchar(max)
= N'SET #text = (SELECT * FROM openrowset(BULK '''+#sqlFile+''', SINGLE_CLOB) as script)'
EXEC sp_executesql #cmd , N'#text nvarchar(max) output', #text = #scriptText OUTPUT
DECLARE #ProcHead nvarchar(max) = N'CREATE or ALTER PROCEDURE '+#procName+ ' AS '+#crlf+'BEGIN'+#crlf
DECLARE #ProcTail nvarchar(max) = #crlf + N'END '
SET #scriptText = #ProcHead + #scriptText + #ProcTail
-- create TestGen stored procedure --
EXEC sys.sp_executesql #scriptText
END