r: "$(fileName)" in a script called from sqlcmd - sql-server

I'm trying to create a script just to run other scripts and do some extra stuff in case of successful or failure.
You have the full code on this link just to try to be clear what I'm trying to achieve.
Basically I want to:
-- DO SOME STUFF HERE
r: "$(fileName)"
-- MORE STUFF HERE
and call it from sqlcmd this way:
sqlcmd -i "RunScript.sql" -v fileName="someFileName.sql" -s server -d database
But I can't, I'm getting the following error:
Msg 102, Level 15, State 1, Server SERVER, Line 19 Incorrect syntax
near 'someFileName.sql'.
So, it seems that the little r: couldn't be used with a parameter on his side.
Just to clarify, someFileName.sql isn't in the SQL Server, but in my machine, so I couldn't use this way to read the file. In fact, I just tried it later.
Is there a workaround to archive this? Any ideas to solve it?

You could break your current RunScript.sql script into separate header and footer SQL scripts and concatenate them together with a SQL script in the middle that is denoted by an input parameter to a CMD script. For example:
RunSQL.CMD consists of:
#ECHO OFF
COPY /V /Y RunScriptHeader.sql + %1 + RunScriptFooter.sql RunScriptTemp.sql
SQLCMD -i "RunScriptTemp.sql" -s server -d database
The /V does a verify on the copy
The /Y suppresses prompting to confirm overwriting an existing file
You would run it as follows:
RunSQL.CMD someFileName.sql

Related

What is wrong with the codes in this BCP utility running on SQL Server?

I have created a BCP utility and I have wrapped it in a bat file. I have then created a daily task using Task Scheduler in Windows Server 2012.
The function of the BCP utility is to rename a file called 'myfile.csv' (located in C:) by adding a date stamp to it and updating the file with the result of a SQL query.
The codes currently stand as follows:
cd:\Program Files\ Microsoft SQL Server\Client SDK\ODBC\110\Tools\Binn
set vardate=%DATE:~4,10%
set varDateWithoutSlashes=%vardate:/=-%
ren C:\myfile.csv myfile_%varDateWithoutSlashes%.csv
bcp "SELECT TOP 100 ReservationStayID,NameTitle,FirstName,LastName,ArrivalDate,DepartureDate FROM MyDatabase.dbo.GuestNameInfo" queryout C:\myfile.csv -t, -c -S [ipaddress] -U sa -P 1234
My problem is that when the task runs, it renames the file correctly with a the date stamp but it seems that the SELECT query does not run as the file is empty (except the headers, which have been pre-loaded by the way).
What is wrong with my codes?
I should also add the following:
Are the double quotes in the select statement above correct? Or should they be single quotes?
Should the ipaddress in my codes above be in square brackets or should I remove them?
I have left the "Location" filed 'as is' in the Task Scheduler (please see screenshot below). Should that be filled? If yes, by what?
Thanks for helping out!

SQL - Automatic results to CSV or Text File

I was wondering if anyone can help.
I have a number of queries in SQL (all in separate *.sql files). I wanted to know if there is a way to run these queries automatically or mass run them to be saved to either a csv or txt file?
Also, I have come variables within these queries which will need to be amended on a weekly bases before the queries are run.
Thanks.
KJ
Could you please provide some additional help in relation to the variables? Previously I would declare and set variables as:
DECLARE #TW_FROM DATETIME
DECLARE #TW_TO DATETIME
SET #TW_FROM = '2015-11-16 00:00:00';
SET #TW_TO = '2015-11-22 23:00:00';
How do I do this using sqlcmd?
Yes, you can use sqlcmd to do this.
First of all - variables. You can refer to your variables in the .sql files using $(variablename) wherever you want to substitue the variable. For example,
use $(dbname);
select $(columnname) from table1 where column= '$(var1)'
You then call sqlcmd with the following command (note the argument -v variables)
sqlcmd -S servername -d database -i "yoursqlfile.sql" -v dbname="database" columnname="column" var1="Fred"
In order to output this to a file, you tag > filename.txt on the end
sqlcmd -S servername -d database -i "yoursqlfile.sql" -v dbname="database" columnname="column" var1="Fred" > filename.txt
If you want to output to a csv, you can also specify the delimiter using the argument -s (note the idfference with the capital S for server). So now we have
sqlcmd -S servername -d database -s "," -i "yoursqlfile.sql" -v dbname="database" columnname="column" var1="Fred" > filename.csv
If you want to output several commands to the same csv or txt file, use >> instead of > as it add to teh bottom of the file, rather than replacing it.
sqlcmd -S servername -d database -s "," -i "yoursqlfile.sql" -v dbname="database" columnname="column" var1="Fred" >> filename.csv
To run this for several scripts, you can put the statements in a batch file, and then change the variables every week.
You could write a batch file that uses sqlcmd:
MSDN sqlcmd
That will allow you to call script files in a loop and output the results to a file.
Convert your current scrips to a Stored Procedure.
You can then pass your variables to that and run the query.
If you have SQL Server agent available (SQL standard or better) you can use this to automate the running of the stored procedures.
Otherwise the same can be achieved with Task Scheduler in windows.
As for exporting to CSV this will be useful.
It depends on where your SQL Server is acutally running. It might be quite tricky to write anything to the location you want.
You could read about BCP.
My suggestion is:
Create an UDF (best is inline-UDF!) from all of your queries within your database. Than call them from EXCEL or any other fitting product. You might want to set up an Excel where all your queries are filled one on each Sheet automatically

Batch for loop in psexec command

I'm trying to use a batch FOR loop inside a psexec. I need to make a script that offers me the possibility to choose the subfolders (I store the items in %list_of_items%) in %local_folder% that are needed to be copied with ncftpput on remote server. I cannot put the entire psexec inside the loop because I dont want to insert every time the password.
The piece of code:
psexec \\remote_server -u DOMAIN\user cmd /c FOR %%i IN "%list_of_items%" DO ("ncftpput -f c:\folders\file_with_creds.cfg -R remote_folder/ %local_folder%/%%i")
Example
I have:
%local_folder%\folder111
%local_folder%\folder222
%local_folder%\folder333
I choose to copy the items folder111 and folder333 so I store them in %list_of_items%. For every item in the list I need to run ncftpput to transfer to remote server the folder but doesnt work....
The error:
"folder111" was unexpected at this time.
cmd exited on remote_server with error code 1.
Can you help me please to find what I'm doing wrong?
Thank you.

BCP utility incorrect syntax

What is incorrect about this syntax?
bcp transitschedule in calendar_dates.txt -T -f calenar_dates.fmt -F 2
I have tried this through sqlcmd and SSMS to a database on Azure. When I run the command I get:
Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'in'.
Yet, the examples here are not very much different syntactically. If I add database name or schema name error shifts towards the period.
Like SQLCMD, BCP is a stand-alone command-prompt utility that must be invoked from a command prompt. If the source text and format files reside on your client, you'll need to add the -S -U and -P parameters like you do with SQLCMD. For example:
bcp databasename.schemaname.transitschedule in calendar_dates.txt -f calenar_dates.fmt -F 2 /S azure-database-server /U azure-database_login /P azure-database-password

SQLCMD Syntax error when running script that runs fine in management studio

When I run the this select '$(''test'')' in SQL Management Studio 2008 it returns $('test')
When I run sqlcmd -S SERVER -E -d DATABASE -q "select $(''test'')" on the command line it returns Sqlcmd: Error: Syntax error at line 1 near command '''.
If I remove the dollar sign it works. Is the "$" a special character?
Is this a sqlcmd bug? How can I change the script to get the desired result.
Yes, $(id) has special semantics in SQLCMD: it is a variable substitution. You can run commands like:
sqlcmd /E /S . /v variable=MyTable /Q "select * from $(variable)"
and this will select from MyTable. As you guess, the /v is the switch to define a variable. SSMS on the other hand does not, by default, interpret the SQL for variable substitution. SSMS can be made to do this, by checking the option 'Open query widows in SQLCMD mode'.
For mode details see Using sqlcmd with Scripting Variables.
the command you are trying to run:
select $('test')
is not valid. As you note, when you remove the "$" it works:
select ('test')
I'm not sure what you are really trying to do, you have three " double quote characters, you could try using this command:
select '$(test)'
which would be:
sqlcmd -S SERVER -E -d DATABASE -q "select ''$(test)''"

Resources