Call sql script using bat file - sql

It is necessary to use the bat file to call the sql script and pass two variables into it, but sql complains about them. Asks to declare scalars.
Here is the bat file itself.
#ECHO OFF
echo SET #arg1 := %2, #arg2 := %3; > commands
copy /b commands + %1 + %2 > nul
"C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\170\Tools\Binn\sqlcmd.exe" -S DESKTOP-OQ8JGR5 -U SA -P 123 -i %1
And sql script.
USE MVA
SELECT sum(number*price2 - number*price1) AS pribil FROM sale,goods
WHERE id=goods AND datepart(month, date)=#arg1 AND shop=#ar2

you can create a stored procedure and call that via sqlcmd from the bat file. for example:
create procedure [SP_count_up]
(
#input int
)
as
begin
select #input + 1
end
go
and call it in you bat file via
sqlcmd -Q "exec dbo.SP_count_up #input=3" -S <server> -d <database>

Related

Pass arguments to a sql file via command line arguments in shell script

I am using SnowSQL to run a SQL script. I have command line parameters which needs to also be passed to the SQL script during my SnowSQL call. Here is what I have:
SQL script (file.sql):
select * from table where cli_id = '$1' and store_id = '$2';
Shell script (run.sh):
snowsql -c credentials -f file.sql
I run this in my terminal with the following command:
sh run.sh 123 555
This isn't working - how can I fix it to pass the parameters to the SQL file correctly?
#!/usr/bin/env bash
snowsql -c credentials -D COLOR="$1" -D SIZE="$2" -f file.sql
And in the SQL file:
SELECT id, name, description IN articles WHERE colour=&COLOR AND size=&SIZE;
See: Using SnowSQL — Snowflake Documentation / Using Variables / Defining While Connecting
Defining While Connecting (-D or --variable Connection Parameter)
To define variables while connecting to Snowflake, on the terminal command line, specify the -D or --variable connection parameters followed by the variable name and value, in the form of <variable_name>=<variable_value>.
For example:
Linux/macOS
$ snowsql ... -D tablename=CENUSTRACKONE --variable db_key=$DB_KEY
Windows
$ snowsql ... -D tablename=CENUSTRACKONE --variable db_key=%DB_KEY%
Try changing the script file.sql to:
select * from table where cli_id = '&cli_id' and store_id = '&store_id';
.. and run.sh should be:
snowsql -c credentials --variable cli_id=$1 --variable store_id=$2 -f file.sql

Run large SQL query from a bat file

I am trying to run a monthly extract from a SQL Express DB using a .bat file called from windows scheduler and the SQL query is large (about 50 lines) and I can't work out how to include such a large script in the bat file without it all being flattened out into one (long) single row of text. Is there a carriage return (or similar) command that I can use to keep the query in the readable SQL format like I have below?
SELECT a.[Application_Number]
,case when c_MNI >0 then
100*(a.monthly_living_allowance +
a.New_Home_Loan_Repayment_Amount +
c_mc)/c_MNI
else 0 end as nsr_calc
,a.[FIN_Total_Net_Service_Ratio] as NSR
,a.Total_Annual_Income_Gross_Total as Annual_Gross
,a.fin_total_annual_income_net1 as Annual_Net
,C_MNI as MNI
,C_MC as MC
,a.[monthly_living_allowance] as MLA
,a.[Manual_MLA]
,a.[Manual_MLA_Flag] ....etc etc...
You can use sqlcmd in your bat file. Put your SQL script in a file, let's say it's DoSomeQuery.sql. Then call sqlcmd in your bat file like this:
sqlcmd -S servername -U user -P password -d DB_Name -i DoSomeQuery.sql
If you have multiple sql files, you can use for command in your bat file like this:
for /r . %%f in (*.sql) do sqlcmd -S servername -U user -P password -d DB_Name -i "%%f"

How to execute SQL script in directory from another script?

Say I have a .sql script stored in c:\scripts\some_script.sql.
What command do I use to execute this script from within another script or stored procedure.
For example
create procedure dbo.sp_execute_script
#script_location varchar(100)
as
execute(#script_location)
-- does not work
go
I am running the scripts in SSMS.
Use xp_cmdshell to run sqlcmd utility to execute your script:
exec xp_cmdshell 'SQLCMD -S <Server> -E -i "C:\path\script.sql"

Can I specify an input sql file with bcp?

How can I specify an input sql file with a long query when using bcp? I tried using the -i option but it keeps complaining about a command-line error with no extra information. Is this possible?
I had this problem today and found a convenient workaround, at least in an ad-hoc situation.
Temporary tables can be created by any user with connect permissions. This means you can also create GLOBAL temporary tables.
Just run your query in enterprise manager (or sql cmd or whatever) using SELECT ...INTO with a global temporary table e.g.
SELECT *
INTO ##mytemptable
FROM SomeTable
WHERE [massive where clause, for example]
You can then use the temporary table in the BCP query with a simple
SELECT * FROM ##mytemptable
Then drop the temp table through enterprise manager
DROP TABLE ##mytemptable
I did other way for fix that.
I create a batch file which read a file and send your content in bcp command. See:
#ECHO off
SETLOCAL EnableDelayedExpansion
SET queryFile=%1
SET outFileName=%2
FOR /F "delims=" %%i IN (%queryFile%) DO SET join=!join! %%i
ECHO %join%
bcp "%join%" queryout %outFileName% /S.\SQLE_CAESAR /d /c /t"|" /T
That script receive two parameters:
Filename which has a query;
Filename for export data;
Execute a script in cmd like that:
export-query.bat query.sql export.txt
I hope helped.
As far as I'm concerned the BCP utility only supports Transact-SQL queries directly written to the command line. Ex:
bcp "SELECT Name FROM AdventureWorks.Sales.Currency" queryout Currency.Name.dat -T -c
According to its reference the "-i" option:
Specifies the name of a response file, containing the responses to the command prompt questions for each data field when a bulk copy is being performed using interactive mode (-n, -c, -w, or -N not specified).
Notice that it differs from the sqlcmd Utility "-i" option:
Identifies the file that contains a batch of SQL statements or stored procedures. Multiple files may be specified that will be read and processed in order (...)
try :
query=$( cat < /file.sql )
export query
bcp "${query}" queryout /home/file.csv
Multi-line queries can be given to bcp easily using powershell:
PS> $query = #'
select *
from <table>
'#
PS> bcp $query queryout <outfile> -d <database> -T -S <server> -c
I had face same issue, may not be a very good approach. However, I did something like the following
bcp "declare #query nvarchar(max) set #query = (SELECT * FROM OPENROWSET(BULK 'F:\tasks\report_v2.sql', SINGLE_CLOB) AS Contents) exec sp_executesql #query" queryout %outFileName% /c /C RAW -S . -U sa -P 123 -d blog /T
And I must say, if you use like global temp table then global temp table is dropped itself of after query executed. you can't use this at some situations
What really worked for me is this:
#ECHO off
setlocal enableextensions enabledelayedexpansion
SET "queryFile=%1"
SET "outFileName=%2"
SET RESULT=
FOR /F "delims=" %%i IN ('type %queryFile%') DO SET RESULT=!RESULT! %%i
echo %RESULT%
rem bcp "%RESULT%" queryout %outFileName% -t^ -r \n -T -k -c -d DB_NAME -S SERVER_NAME
type file is the equivalent of cat file in unix
What I did with complex queries was create a stored procedure with the desired statement and call it from BCP:
bcp "exec db.schema.stored_procedure" queryout "c:\file.txt" -T -S localhost -t "|" -c
This worked great for me. Greetings!
I made my own script (called of bulk.sh) to do this (not optimal and not best practice... The script is too ugly, but very functional).
#!/bin/bash
input="SQL_FILE.sql"
count=0
const=1000
lines=()
mkdir -p bulk
while IFS= read -r line
do
lines+=("$line")
count=$((count+1))
check=$((count % const))
if [[ $check -eq 0 ]]; then
bulk="${lines[*]}"
unset lines
number=$(printf "%010d" $count)
echo $bulk > "bulk/bulk${number}.sql"
bulk=""
fi
done < "$input"
FILES="bulk/*"
for f in $FILES
do
echo "Processing $f file..."
sqlcmd -S SERVER -d DATABASE -U USER -P "PASSWORD" -i "$f"
sleep 2s
done
You can try it, with:
$ docker run -v /path/to/your/sql/file/folder:/backup -it mcr.microsoft.com/mssql-tools
$ bash bulk.sh

How do I run a script using a BAT file?

I would like to have a BAT file open a sql server script. Currently I have this code in the sql file:
declare #path varchar(255), #mydb varchar(50)
SELECT #mydb = 'timeclockplus'
select #path = 'C:\Program Files\Microsoft SQL Server\MSSQL.2\MSSQL\Backup\'
+ #mydb + '-' + convert(varchar(8),getdate(),112) + '.bak'
BACKUP DATABASE #mydb TO DISK = #path
How do I open this SQL file from a BAT file?
I am currently trying to run it like this:
C:\Program Files\Microsoft SQL Server\80\Tools\Binn\osql -E
-S Sql server-hl7\timeclockplus timeclockplus.sql -oresults.txt
but OSQL does not exist in the BINN directory,
You should invoke the sqlcmd command-line tool from your batch file. Assuming your sql file is "backup.sql", the command line would be something like:
sqlcmd -E -S yoursqlinstance -i backup.sql
-E uses trusted connection, replace with -U and -P if you need to specify a SQL username and password. See also this article with examples.
sqlcmd -S 127.0.0.1 /E -i MySqlScript.sql
Replace /E with /U and /P if you don't have trusted connection
If you want a much better answer, here it is:
#echo off
SETLOCAL ENABLEDELAYEDEXPANSION
:: batch file for sql query
SET FIELDVAL=Empty
SET DBNAME=MYDB
SET SQLSTRING=SELECT column_name(s)^
FROM table_name1^
INNER JOIN table_name2^
ON table_name1.column_name=table_name2.column_name^
AND table_name2.field=%FIELDVAL%
ECHO !SQLSTRING!
ECHO.
sqlcmd.exe -b -S localhost -E -d !DBNAME! -Q "!SQLSTRING!" -W
ECHO Query is done. Hit any key to close this window....
pause>nul
Start > Run > Type Cmd.
MyDrive:\Mypath\Mybat.bat
=)