Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqlcmd return only count - suppress text

Tags:

bash

sqlcmd

I have a bash file which executes a SQLCMD query to check for the existence of a database:

sqlcmd -S localhost -U sa -P $SA_PASSWORD -d master -Q "SET NOCOUNT ON SELECT count(*) FROM master.sys.databases WHERE name = N'MyDatabaseHere'")

I tried adding the SET NOCOUNT ON but it still outputs like this:

------

1

I am assigning the result to a variable and I want to be able to check it like this

myvariable == 1

Is there a way to do this?

like image 985
user3437721 Avatar asked Jul 02 '26 01:07

user3437721


1 Answers

Took me a while but I found a solution only using sqlcmd.

You need to use -W -h-1 -k

-W removes trailing space

-h-1 removes headers

-k Removes all control characters, such as tabs and new line characters from the output.

TABLENAME=$(/opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P $SA_PASSWORD -d master -W -h-1 -k -Q "SET NOCOUNT ON SELECT name FROM master.sys.databases WHERE name = N'MyDatabaseNameHere'")
like image 162
user3437721 Avatar answered Jul 05 '26 00:07

user3437721



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!