4

I am trying to extract data from some of my tables using sqlcmd utility as SSMS does not generate appropriate csv-s for me.

My issue: all csv extract includes trailing spaces according to table definitions (I mean field length) regardless of using char, varchar, nvarchar, etc...

When using sqlcmd utility eg with following options:

sqlcmd -S . -d /*databasename*/ -E -s, -W -Q "SELECT * FROM /*tablename*/" > C:\Test.csv

it is still contains trailing spaces, eg:

,"273 ",

any hints or tips to do this in SSMS and/or correcting my parameters for SQLCMD?

asked Jul 30, 2020 at 6:58
1
  • 1
    Sounds as if that column is defined as char(n) which will contain fixed length, blank padded values. Commented Jul 30, 2020 at 7:16

2 Answers 2

2

Despite how the SQLCMD usage screen (SQLCMD -?) describes the -W parameter:

[-W remove trailing spaces]

the actual purpose of this parameter is not to remove existing trailing spaces but rather to skip padding a value with spaces. If a string value already has trailing spaces of its own, they cannot be removed if you simply specify the -W parameter.

As far as I can see, there is no way to resolve this issue with parameters. You will have to either manipulate the output with text processing utilities or generate the values without the trailing spaces in the first place. For the latter you can use the RTRIM() function, but that, of course, means you will have to replace the SELECT * with an actual column list, where some columns would be computed columns:

SELECT
 ...
 RTRIM(SomeStringColumn) AS SomeStringColumn,
 ...
FROM
 ...
answered Jul 30, 2020 at 10:24
1

Did you try these sqlcmd parameters?

sqlcmd
 -o output_file 
 -W (remove trailing spaces)
Paul White
95.4k30 gold badges440 silver badges689 bronze badges
answered Jul 30, 2020 at 8:51
2
  • 1
    The OP's command line has the -W parameter, so apparently yes, the OP did try that option. From my own experience I can confirm that it doesn't work for char columns, as @a_horse_with_no_name suggested in a comment under the question. Commented Jul 30, 2020 at 9:06
  • so he´ll have to convert(varchar(10), thecolumn) in that case Commented Jul 30, 2020 at 9:13

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.