Search code examples
bashsqlcmd

sqlcmd return only count - suppress text


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?


Solution

  • 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'")