Running SQL script using SQLCMD and export to CSV file

  • Hello

    I have a script that has been written to obtain some data from our SQL Express instance. the script works with no issues. However i need to automate this. I was going to automate this using a SQLCMD -S then call the script which is saved on the server. I dont thing this is going to be an issue, the issue is the results. how can i get these to be exported to CSV file?

    Can someone let me know the code or the commands needed to obtain this?

    Regards

    Gareth

    grc1uk@yahoo.com

  • Hi,

    Try this command:

    sqlcmd -Sservername -d myDB -E -Q "select col1, col2, col3 from SomeTable" -o "MyData.csv" -h-1 -s"," -w 700

    -h-1 removes column name headers from the result

    -s"," sets the column seperator to ,

    -w 700 sets the row width to 700 chars (this will need to be as wide as the longest row or it will wrap to the next line)

    ----------------------------------------------------------------
    **"There is only one difference between dream and aim. Dream requires Soundless sleep to see…Where as Aim Requires Sleepless Efforts to Achieve":-) **

  • Thanks for this,

    sorry for the delayed reply.

    i will give this ago. the script will need to reference more than one DB but i assume i will be able to tweek what you have put

    Many thanks

    Gareth

  • Hi,

    Also, you can try out using -i D:\SQL\Script1.sql in place of -Q if you are directly calling a script. -i indicates the script file path.

    Have a nice day !

    ----------------------------------------------------------------
    **"There is only one difference between dream and aim. Dream requires Soundless sleep to see…Where as Aim Requires Sleepless Efforts to Achieve":-) **

  • Once again thanks, that has worked a treat. Think im going to see if it can date stamp the output that is created so that more than one file can exist, but that was very helpfull

    Regards

    Gareth

  • Hi, you have posted below string:

    sqlcmd -Sservername -d myDB -E -Q "select col1, col2, col3 from SomeTable" -o "MyData.csv" -h-1 -s"," -w 700

    In the above string you are deviding data with 'comma' suparator, but what if we already have 'comma' in between the data not between the columns. Still it will grab the data with out overlaping.

    Ex:

    col1 col2

    ----- -----

    abc g,h,i

    def jk,l

Viewing 6 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic. Login to reply