How to execute sql file using another sql file MSQL - sql

Im creating database which need few sql scripts. Running them one by one is not effective , so I wanted to create main sql query which will load all files. I tried this :
Declare
#DBServerName Varchar(100),
#DBName Varchar(100),
#FilePathName Varchar(100),
#strSql varchar(1000)
Set #DBServerName='USER-PC'-- Server Name
Set #DBName='testo' -- DB Name
Set #FilePathName='some path here'
Set #strSql= 'sqlcmd -S ' + #DBServerName + ' -d ' + #DBName + ' -i ' + #FilePathName
EXEC xp_cmdshell #strSql
After executing this, It is showing that my query was executed succesfully but in my database nothing is appearing. Ive seen lot of websites but there is no working answear.

I don't think you want xp_cmdshell here. If you want to execute dynamic SQL you should be using the code below:
sp_executesql #strsql;

Related

gpg encryption in xp_cmdshell

I am trying to encrypt a .csv file using gpg in xp_cmdshell command in sql server 2012.
When I use gpg through xp_cmdshell, it says gpg is not recognized as an internal or external command.
But this works perfectly on windows cmd.
How should I configure my sql server to accept this command. Please advice.
select #encrypt = 'gpg -e -r ' + #sEncryptionKey+ ' '+ #sPath + #tempdataFolder+'\'+ #sFileName
exec master..xp_cmdshell #encrypt
To remedy the error you are indicating above, simply add the full path to gpg.exe in your code.
select #encrypt = 'c:\gpg\gpg.exe -e -r ' + #sEncryptionKey+ ' '+ #sPath + #tempdataFolder+'\'+ #sFileName
exec master..xp_cmdshell #encrypt
For comparison, this is how I have done this in the past via SSIS; be sure you provide the exact full path to your executable... we are using gpg4win (gpg2.exe) in this example.
You may also want to wrap each parameter in " " to handle file names/paths with spaces better.
DECLARE #sKeyEmail VARCHAR(100), #sInFile VARCHAR(100), #sOutFile VARCHAR(100), #SQL VARCHAR(1000)
SET #sInFile = 'c:\temp\somefile.xls'
SET #sOutFile = 'c:\temp\somefile.xls.gpg'
SET #sKeyEmail = 'user#domain.com'
SET #SQL = 'EXEC master.dbo.xp_cmdshell ''C:\Progra~1\GNU\GnuPG\gpg2 -o ' +#sOutFile+ ' -e -r ' +#sKeyEmail + ' ' +#sInFile+ ''''
PRINT #SQL
-- EXEC sp_execute #SQL

How to run multiple SQL scripts, in SSMS, against SQL Azure?

I would like to execute multiple SQL (*.sql) TSQL script files, in SSMS, against a SQL Azure DB. I happen to be using SSMS 2008 R2
The code, I tried to execute in a SSMS query window, linked to the relevant DB instance, as picked up from a previous SO question, was :
/*
execute a list of .sql files against the server and DB specified
*/
SET NOCOUNT ON
SET XACT_ABORT ON
BEGIN TRAN
DECLARE #DBServerName VARCHAR(100) = 'DBServerName '
DECLARE #DBName VARCHAR(100) = 'DBName'
DECLARE #FilePath VARCHAR(200) = 'c:\temp\scripts'
/*
create a holder for all filenames to be executed
*/
DECLARE #FileList TABLE (Files NVARCHAR(MAX))
INSERT INTO #FileList VALUES ('script1.Sql')
INSERT INTO #FileList VALUES ('script2.Sql')
INSERT INTO #FileList VALUES ('script3.Sql')
WHILE (SELECT COUNT(Files) FROM #FileList) > 0
BEGIN
/*
execute each file one at a time
*/
DECLARE #FileName NVARCHAR(MAX) = (SELECT TOP(1) Files FROM #FileList)
DECLARE #command VARCHAR(500) = 'sqlcmd -S ' + #DBServerName + ' -d ' + #DBName + ' -i "' + #FilePath + #Filename +'"'
EXEC xp_cmdshell #command
PRINT 'EXECUTED: ' + #FileName
DELETE FROM #FileList WHERE Files = #FileName
END
COMMIT TRAN
Unfortunately SQL Azure does not support "xp_cmdshell".
How can I execute multiple SQL scripts for an Azure SQL instance?
Thanks in advance.
P.S I am aware of how one can open a file in SSMS
When using SSMS the script is send to the server and then executed there. As I mentioned in the comment in SQL Database the server does not have access to files on the machines they are hosted on nor can you actually upload them to these machines. So you approach does not work. Opening files that you have locally on your machine is also not possible.
To execute a set of scripts from your local machine against a SQL Database you have to translate your SQL script for example into a PowerShell script:
Get-ChildItem "c:\temp\scripts" -Filter script*.sql | `
Foreach-Object{
Write-Host 'Executing' $_.FullName
sqlcmd -U <username>#<server> -P <Password> -S <server>.database.windows.net -d <DatabaseName> -i $_.FullName
}

Output SQL Server table to XML in a directory on the server

I'm trying to export my
select column1, column2
from table1
into a XML file and save it into a directory of c:\Test\ on the server.
I would also like the file to be overwritten when the i run the query again with same output xml name.
Is there away of doing this without going through creating a how SSIS Job. I have used the feature FOR XML AUTO and FOR XML PATH but these do not give you a formed XML that will open as well as the option to save into a location.
Any ideas on how to do this would be good!
I have run the following after Aruns Comment :
I have run the following :
DECLARE #fileName VARCHAR(50) DECLARE #sqlStr VARCHAR(1000) DECLARE #sqlCmd VARCHAR(1000)
SET #fileName = 'C:\test.xml' SET #sqlStr = 'select TOP 50 [Key_Scores], [Total_Scores] from Futures.[dbo].[Aco_Scores] FOR XML PATH (''Key_Scores''), ROOT (''Key_Scores.Total_Scores'')'
SET #sqlCmd = 'bcp "' + #sqlStr + '" queryout ' + #fileName + ' -w -T' EXEC xp_cmdshell #sqlCmd
Table is called Aco_Scores and the 2 columns are called Key_Scores and Total_Scores.
Error = [Microsoft][SQL Server Native Client 11.0][SQL Server]Invalid object name 'Futures.dbo.Aco_Scores'.
Error = [Microsoft][SQL Server Native Client 11.0]Unable to resolve column level collations
I've entered my columns wrong?
My New Query i have tried is :
This query produces an non opening XML file, Actually i have tried the PATH and AUTO but no joy. -- URL Summary Rotary
DECLARE #fileName VARCHAR(50) DECLARE #sqlStr VARCHAR(1000) DECLARE #sqlCmd VARCHAR(1000)
SET #fileName = 'C:\XML\Summary_Rotary.XML' SET #sqlStr = 'select TOP 8 [Top_8_Hits], [Best_Score], [Lowest_Score], [Average_Score], [Final_Rating] from Futures.[dbo].[Summary_Rotary] FOR XML AUTO'
SET #sqlCmd = 'bcp "' + #sqlStr + '" queryout ' + #fileName + ' -w -T' EXEC xp_cmdshell #sqlCmd
Which produces a non working XML
There are several ways of doing this.
First in your code you can add FOR XML AUTO that will display results in XML.
Then, you can use SSMS to export results to file.
Tools -> Options -> Query Results -> Sql Server -> General -> Default destination... for results to file or Ctrl + Shift + F
Lots of T-SQL code based examples here.

Why I cannot change database dynamically SQL Server 2008

The following is not working and I am definitely missing the obvious but would be nice if somebody could explain why is not working. I need to change db dynamically.
The print out looks good but does not change db in the SQL Server drop down.
DECLARE #tempSql nvarchar(4000);
DECLARE #FinalSQL nvarchar(4000);
DECLARE #dbName varchar(100);
SET #dbName = 'Pubs';
SET #tempSql = 'SELECT DB_NAME()';
SET #FinalSQL = 'USE ' + #dbName + '; EXEC sp_executesql N''' + #tempSql + '''';
EXEC (#FinalSQL)
If SQLCMD mode is an option for your (within SSMS, for example), you can do this:
:setvar dbname Pubs
USE [$(dbname)]
SELECT DB_NAME()
Or, your original syntax was pretty close. Try this:
DECLARE #db AS NVARCHAR(258);
SET #db = QUOTENAME(N'Pubs');
EXEC(N'USE ' + #db + N'; EXEC(''SELECT DB_NAME();'');');
GO
There is a way to access data from a specific database by using this syntax :
FROM DatabaseName..TableName
maybe you should use a dynamic database name in your scripts, then change it whenever you need
otherwise, take a look at this : http://www.sqlteam.com/article/selecting-data-from-different-databases
Executing the dynamic SQL is done in a scope of its own.
So you do change the current database, as you see, but only within the scope of the dynamic SQL.

Is it possible to execute a text file from SQL query?

I have a number of generated .sql files that I want to run in succession. I'd like to run them from a SQL statement in a query (i.e. Query Analyzer/Server Management Studio).
Is it possible to do something like this and if so what is the syntax for doing this?
I'm hoping for something like:
exec 'c:\temp\file01.sql'
exec 'c:\temp\file02.sql'
I am using SQL Server 2005 and running queries in management studio.
use xp_cmdshell and sqlcmd
EXEC xp_cmdshell 'sqlcmd -S ' + #DBServerName + ' -d ' + #DBName + ' -i ' + #FilePathName
Very helpful thanks, see also this link:
Execute SQL Server scripts
for a similar example.
To turn xp_cmdshell on and off see below:
On
SET NOCOUNT ON
EXEC master.dbo.sp_configure 'show advanced options', 1
RECONFIGURE
EXEC master.dbo.sp_configure 'xp_cmdshell', 1
RECONFIGURE
Off
EXEC master.dbo.sp_configure 'xp_cmdshell', 0
RECONFIGURE
EXEC master.dbo.sp_configure 'show advanced options', 0
RECONFIGURE
SET NOCOUNT OFF
Or just use openrowset to read your script into a variable and execute it (sorry for reviving an 8 years old topic):
DECLARE #SQL varchar(MAX)
SELECT #SQL = BulkColumn
FROM OPENROWSET
( BULK 'MeinPfad\MeinSkript.sql'
, SINGLE_BLOB ) AS MYTABLE
--PRINT #sql
EXEC (#sql)
This is what I use. Works well and is simple to reuse. It can be changed to read all files in the directory, but this way I get to control which ones to execute.
/*
execute a list of .sql files against the server and DB specified
*/
SET NOCOUNT ON
SET XACT_ABORT ON
BEGIN TRAN
DECLARE #DBServerName VARCHAR(100) = 'servername'
DECLARE #DBName VARCHAR(100) = 'db name'
DECLARE #FilePath VARCHAR(200) = 'path to scrips\'
/*
create a holder for all filenames to be executed
*/
DECLARE #FileList TABLE (Files NVARCHAR(MAX))
INSERT INTO #FileList VALUES ('script 1.sql')
INSERT INTO #FileList VALUES ('script 2.sql')
INSERT INTO #FileList VALUES ('script X.sql')
WHILE (SELECT COUNT(Files) FROM #FileList) > 0
BEGIN
/*
execute each file one at a time
*/
DECLARE #FileName NVARCHAR(MAX) = (SELECT TOP(1) Files FROM #FileList)
DECLARE #command VARCHAR(500) = 'sqlcmd -S ' + #DBServerName + ' -d ' + #DBName + ' -i "' + #FilePath + #Filename +'"'
EXEC xp_cmdshell #command
PRINT 'EXECUTED: ' + #FileName
DELETE FROM #FileList WHERE Files = #FileName
END
COMMIT TRAN
I wouldn't recommended doing this, but if you really have to then the extended stored procedure xp_cmdshell is what you want. You will have to first read the contents of the file into a variable and then use something like this:
DECLARE #cmd sysname, #var sysname
SET #var = 'Hello world'
SET #cmd = 'echo ' + #var + ' > var_out.txt'
EXEC master..xp_cmdshell #cmd
Note: xp_cmdshell runs commands in the background, because of this, it must not be used to run programs that require user input.
Take a look at OSQL. This utility lets you run SQL from the command prompt. It's easy to get installed on a system, I think it comes with the free SQL Server Express.
Using the osql Utility
A qick search of "OSQL" on stack overflow shows a lot of stuff is available.
The main thing to handle properly is the user and password account parameters that get passed in on the command line. I have seen batch files that use NT file access permissions to control the file with the password and then using this file's contents to get the script started. You could also write a quick C# or VB program to run it using the Process class.
For Windows Authentication, if you are running as another user:
Open Command Prompt as your Windows user (Right click on it, Open File Location, Shift + Right Click, Run as a different user)
sqlcmd -S localhost\SQLEXPRESS -d DatabaseName-i "c:\temp\script.sql"
Or if you are using Sql Server user:
sqlcmd -S localhost\SQLEXPRESS -d DatabaseName-i "c:\temp\script.sql" -U UserName -P Password
Replace localhost\SQLEXPRESS with you server name if not local server.
Open windows command line (CMD)
sqlcmd -S localhost -d NorthWind -i "C:\MyScript.sql"
For anybody stumbling onto this question like I did and might find this useful, I liked Bruce Thompson's answer (which ran SQL from files in a loop), but I preferred Pesche Helfer's approach to file execution (as it avoided using xp_cmdshell).
So I combined the two (and tweaked it slightly so it runs everything from a folder instead of a manually created list):
DECLARE #Dir NVARCHAR(512) = 'd:\SQLScriptsDirectory'
DECLARE #FileList TABLE (
subdirectory NVARCHAR(512),
depth int,
[file] bit
)
INSERT #FileList
EXEC Master.dbo.xp_DirTree #Dir,1,1
WHILE (SELECT COUNT(*) FROM #FileList) > 0
BEGIN
DECLARE #FileName NVARCHAR(MAX) = (SELECT TOP(1) subdirectory FROM #FileList)
DECLARE #FullPath NVARCHAR(MAX) = #Dir + '\' + #FileName
DECLARE #SQL NVARCHAR(MAX)
DECLARE #SQL_TO_EXEC NVARCHAR(MAX)
SELECT #SQL_TO_EXEC = 'select #SQL = BulkColumn
FROM OPENROWSET
( BULK ''' + #FullPath + '''
, SINGLE_BLOB ) AS MYTABLE'
DECLARE #parmsdeclare NVARCHAR(4000) = '#SQL varchar(max) OUTPUT'
EXEC sp_executesql #stmt = #SQL_TO_EXEC
, #params = #parmsdeclare
, #SQL = #SQL OUTPUT
EXEC (#sql)
DELETE FROM #FileList WHERE subdirectory = #FileName
PRINT 'EXECUTED: ' + #FileName
END