Linux SQL Server query with dynamic data? - sql-server

I am trying to run a query from a shell script
SELECT count(*) FROM MyTable where sessionid = 123
I can do:
bsqldb -U myname -P mypass -S myserv -i getcount.sql
But that means the sessionid is hardcoded to 123
I need to have the sessionid pulled in from the shell script calling the bsqldb comment
How can I pass the sessionid as a variable?

echo "SELECT ${foo} FROM ${bar}" | bsqldb -U myname -P mypass -S myserv -i -
Watch out for SQL injection though.

Seems the best way was to just create a tmp.sql file from the bash script itself and use that as my input:
echo "SELECT * FROM $TABLE WHERE SessionID = $SESS_ID" > tmp.sql
result=$(bsqldb -U $USER -S $SERV -P $PASS -i tmp.sql -q)
rm -f tmp.sql
Thanks all!

Related

Update Local SQL Server with a Bash Script

Question:
What is the correct format to use in my bash script to be able to run the -Q option?
Case: Update local database from S3 every night to run reports on our on-premise server
Code:
#!/bin/bash
#get latest file from S3
BACKUP_MARKETING=`aws s3 ls [some_folder]/[some_subfolder]/ --recursive | sort | tail -n 1 | awk '{print $4}'`
#download the file locally
aws s3 cp s3://[some_folder]/$BACKUP_MARKETING /var/opt/mssql/backup/marketing
#get the file name
BAK_MARKETING=`find [folder]/ -type f -name "*.bak"`
#drop the database to avoid conflicts from not backing it up
/opt/mssql-tools/bin/sqlcmd -S localhost -U [username] -P '[password]' -Q 'DROP DATABASE [db_name]'
#restore the database
/opt/mssql-tools/bin/sqlcmd -S localhost -U [username] -P '[password]' -Q RESTORE DATABASE "[db_name]" FROM DISK = "/var/opt/mssql/backup/$BAK_MARKETING" WITH MOVE "[db_name]" TO "/var/opt/mssql/data/[db_name].MDF", MOVE "[db_name]_log" TO "/var/opt/mssql/data/[db_name].LDF"
Error
Sqlcmd: 'DATABASE" "[db_name]" "FROM" "DISK" "=" "/var/opt/mssql/backup/marketing/[db_name].bak" "WITH" "MOVE" "[db_name]" "TO" "/var/opt/mssql/data/[db_name].MDF," "MOVE" "[db_name]_log" "TO" "/var/opt/mssql/data/[db_name].LDF': Unexpected argument. Enter '-?' for help.
Apparently I had to concatenate my variables on the SQL command. Here is the working version plus I added the REPLACE option to it
/opt/mssql-tools/bin/sqlcmd -S localhost -U [username] -P '[password]' -Q 'RESTORE DATABASE [db_name] FROM DISK = "/var/opt/mssql/backup/'**$BAK_FILE**'" WITH REPLACE, MOVE "[db_name]" TO "/var/opt/mssql/data/[db_name].MDF", MOVE "[db_name]_Log" TO "/var/opt/mssql/data/[db_name].LDF"'
Could you not use the -i Option instead?
I had some problems as well using Q, so i replaced it with -i and placed the code within a .sql file instead.
I ended up with;
SET SQLusername=sa
SET SQLpassword=password
SET SQLserver=dnsnameorIp
SET SQLdatabase=databasename
sqlcmd -U %SQLusername% -P %SQLpassword% -S %SQLserver% -d %SQLdatabase% -i mycode.sql -o outputResult.txt

Retrieve rows in DB corresponding to particular ID using kubectl

I am trying to fetch the no. of rows for a particular ID using kubectl but instead getting some extra data.
Command:
kubectl exec abc-db-0 -n cicd --kubeconfig /root/admin.conf -- bash -c "psql -U postgres -d db -f /tmp/queryInstanceId.sql -v v1=full_test | grep [0-9]"
Actual Output of above command:
Defaulting container name to abc-db.
Use 'kubectl describe pod/abc-db-0 -n cicd' to see all of the containers in this pod.
(0 rows)
Expected Output:
(0 rows)
Could anyone please let me know what I am doing wrong here?
Note:
The first 2 lines always comes when we login to the DB manually but in output I only want (0 rows)
The first two lines are output by kubectl exec because the Pod has multiple containers. It is sort of a warning that it picked the first one, which might not be the one you wanted use.
You can specify the target container in your command (-c containername):
kubectl exec abc-db-0 -n cicd --kubeconfig /root/admin.conf -c abc-db -- bash -c "psql -U postgres -d db -f /tmp/queryInstanceId.sql -v v1=full_test | grep [0-9]"
Or you can redirect the standard error with kubectl ... 2>/dev/null (os specific):
kubectl exec abc-db-0 -n cicd --kubeconfig /root/admin.conf -c -- bash -c "psql -U postgres -d db -f /tmp/queryInstanceId.sql -v v1=full_test | grep [0-9]" 2>/dev/null

-X option not disable sql commands in sqlcmd

I use sqlcmd to execute large sql file which insert multiple of records into database. So when sqlcmd run it display a error message like "syntax error near 'Ed'..." . I known Ed is sql commands and i found -X will disable that kind of commands but it is not work.
My command like this:
sqlcmd -S "tcp:ip,1433" -U "sa" -P "pass" -d "dbname" -c "GO" -k 1 -f 65001 -i "C:\sql.sql" -X -x
My sql file content:
Go
insert into tablename (title) values (N'title
Ed some more data
some more data
some more data')
Go
insert into tablename (title) values (N'title
Ed some more data
some more data
some more data')
Go
Could you give me some help? please.
Thanks you.
It use -X[1] instead of -X.
sqlcmd -S "tcp:ip,1433" -U "sa" -P "pass" -d "dbname" -c "GO" -k 1 -f 65001 -i "C:\sql.sql" -X[1]

How to execute a script through sqlcmd in MS Sql server

I got a .sql file in which {0} kind of things used. I would like to know how can i pass values in the sqlcmd for {0} variable.
Sample script (test.sql):
GO
PRINT '{0}'
GO
And I am trying to executing through this command line
sqlcmd -S . -d master -E -i test.sql
But, where should i pass the parameter?
Just Try as below:
test.sql
GO
Print $var
GO
sqlcmd -S . -d master -E -i test.sql -v var="helloWorld"
You can use the -v switch to pass in variables:
sqlcmd -S . -d master -E -i test.sql -v varPrintMe="{0}"
Then you'll need to put the variables in $() in your sql script:
GO
PRINT $('varPrintMe')
GO

how do i pass in a command to sqsh and get the output to a file in one go?

I'm trying to set up a simple loop to periodically query a database table in bash. Normally I seem to have to do:
sqsh -s SERV -U user -P passwd -D db -L bcp_colsep=','
then within sqsh I have to type:
select * from some_table where foo=bar
\go -m bcp > /path/to/output.out
I was trying to use the -C option to sqsh to pass in the command like this:
sqsh -s SERV -U user -P passwd -D db -L bcp_colsep=',' -C 'select * from some_table where foo=bar \go -m bcp > /path/to/output.out'
but I keep getting:
Incorrect syntax near '\'.
How can I get the desired effect?
When you use the -C option to pass on a SQL statement to sqsh, the \go command will be implicitly executed. To get the output in 'bcp' result style you need to set the variable 'style=bcp' using the -L parameter or use -mbcp as a commandline parameter and just redirect the output to a file, or use the sqsh -o parameter to specify a filename for output. So basically your command would look like:
sqsh -S SERV -U user -P passwd -D db -L bcp_colsep=',' -m bcp \
-C 'select * from some_table where foo=bar' > /path/to/output.out
HTH, Martin

Resources