Search code examples
linuxt-sqlbashshellfreetds

freeTDS bash: Executing sql queries in Microsoft SQL server


I am able to connect to a Microsoft SQL Server 2008 instance via a Mint Linux VM using freeTSD and command line to execute sql statements on it. Now I want automate this in a bash script. I am able to successfully login in my bash script:

TDSVER=8.0 tsql -H servername -p 1433 -D dbadmin -U domain\\Administrator -P password

I then have my SQL query:

USE dbname GO delete from schema.tableA where ID > 5 GO delete from schema.tableB where ID > 5 GO delete from schema.tableC where ID > 5 GO exit

This works when doing manually via freeTSD command line, but not when I put in bash file. I followed this post: freeTSD & bash.

Here is my bash script sample:

echo "USE dbname GO delete from schema.tableA where userid > 5 go delete from schema.tableB where userid > 5 go delete from schema.tableC where ID > 5 GO exit" > tempfile | TDSVER=8.0 tsql -H servername -p 1433 -D dbname -U domain\\Administrator -P password < tempfile

the output of the bash script is:

locale is "en_US.UTF-8"
locale charset is "UTF-8"
Default database being set to sbdb
1> 2> 3> 4> 5> 6> 7> 8> 

and then the rest of my script is executed.

Can someone give me a step by step answer to my problem ?


Solution

  • I'm not sure how your sample can work at all.

    Here is my bash script sample:

    echo "USE dbname .... exit" > tempfile | TDSVER=8.0 tsql -H servername -p 1433 -D dbname -U domain\\Administrator -P password < tempfile
    # ------------------------------------^^^^ ---- pipe char?
    

    Try using a ';' char.

    echo "USE dbname .... exit" > tempfile ; TDSVER=8.0 tsql -H servername -p 1433 -D dbname -U domain\\Administrator -P password < tempfile
    # ------------------------------------^^^^ ---- semi-colon
    

    Better yet, use shell's "here documents".

    TDSVER=8.0 tsql -H servername -p 1433 -D dbname -U domain\\Administrator -P password <<EOS
         USE dbname 
         GO 
         delete from schema.tableA where userid > 5 
         go 
         delete from schema.tableB where userid > 5 
         go 
         delete from schema.tableC where ID > 5 
         GO 
         exit
      EOS
    

    IHTH.

    Current command line input:

    echo "delete from table where userid > 5
    go
    delete from table where userid > 5
    go
    delete from table where ID > 5
    GO
    exit" < /tmp/tempfile; TDSDUMP=/tmp/freetds.log TDSVER=8.0 tsql -H servername -p 1433 -D dbname -U Administrator -P password <<EOS