Monday, July 10, 2023

Why and How to use sqlcmd in bash script ?

 Why ?

SQLCMD is a command line utility to be used to run T-SQL for MS SQL server, below I will show how to use it. I have create this to redirect and append the output to the file by date at every execute.


How ?


1- create sql file( myscript.sql) contain whatever script you need to execute.

Use master

Go

Select @@version

go


2- Create bat file contains the script to execute the above sql query:

@echo off

:: to get the date

for /f "delims=" %%a in ('powershell get-date((get-date^).addDays(-1^)^) -uformat "%%Y%%m%%d"') do set date=%%a

:: to run the sql file

sqlcmd -S <server/instane> -U <sqllogin> -P "password" -i C:\path_to_file\myscript.sql >> C:\path_to_file\output%date%.txt

 

:: to print the output file on screen

type C:\path_to_file\output%date%.txt

 

:: pause the screen

set /p delExit=Press the ENTER key to exit...:

 

note : you can't use os authentication for remote sqlcmd in -U , -U used for sql login user only.

No comments:

Post a Comment

Why and How to install Grid 19c on RHEL 8?

  Why ? Simply we will be requested to install Oracle Grid RAC DB on Redhat RHEL 8, below is my note for this installation . How ? 1-  OS in...