Search code examples
sqlcmd

SQLCMD issues with SQL keywords


I have a SQLCMD that almost works like I want:

SQLCMD -s"," -S servername -U username -d databasename -W -o 
"mydatafile.csv” -Q "SET NOCOUNT ON 
SELECT Account,'""' + cast ([ColDescription] as 
nvarchar(100)) + '""' as ColumnDescription" FROM myTable

But once I add keywords like REPLACE or TRIM into the SQL statement, or even if I use CASE statements, I get 'Unexpected Argument -press ? for help' from the CMD

SQLCMD -s"," -S servername -U username -d databasename -W -o 
"mydatafile.csv” -Q "SET NOCOUNT ON 
SELECT Account,'""' + REPLACE(cast ([ColDescription] as nvarchar(100)),'"','""') + '""' as 
ColumnDescription" FROM myTable

Is it because everything in SQL that I'm trying to use happens to be a keyword in CMD too? Or, am I just missing something really big? The SQL queries themselves work fine and return my expected result set in SSMS, so I know the SQL is valid.


Solution

  • I found a way around my issue by using the QUOTENAME function in my SQL like this:

    SQLCMD -s"," -S servername -U username -d databasename -W -o 
    "mydatafile.csv” -Q "SET NOCOUNT ON 
    SELECT Account, QUOTENAME(cast ([ColDescription] as nvarchar(100)),'""') as 
    ColumnDescription" FROM myTable
    

    Where I use 2 double-quote characters in the QUOTENAME function. But, I would still be interested in other responses who can confirm/tell me more about WHY my other solutions using CASE, REPLACE, etc. didn't work in CMD. I still think those should have worked too...or whether knowing more about CMD would help me find escape characters that may have helped.