BCP Copy

  • I am copying contents of 2 csv files to at third one.

    It works with this command:

    exec master..xp_cmdshell 'copy /b "c:\shared\header.csv" + "c:\shared\body.csv" c:\shared\result.csv'

    But when I use variable for the path and filename and retaining the single and double quote use:

    exec master..xp_cmdshell 'copy /b "' + @filePath + @fileNameH + '"' + ' + "' + @filePath + @fileNameB + '" ' + ' ' + @filePath+@filename

    Incorrect syntax near '+'. results. Indicating an error in the first + sign.

    nb: copy /b is followed by a double quote and a single quote.

    Any thoughts will be appreciated.


  • If you want help, you'll have to show the rest of the code i.e. how you declare and populate the variables.

    To debug this, you should put the whole command you are passing into a string, then print the string out and see what exactly you pass to xp_cmdshell

  • You will have to take the value to a variable first then you may need to make EXEC call. EXEC call expects variable only and dont perform concatenation operation.

    So a working syntax may look like

    Declare @STR Varchar(500)

    Set @STR= 'copy /b "' + @filePath + @fileNameH + '"' + ' + "' + @filePath + @fileNameB + '" ' + ' ' + @filePath+@filename

    exec master..xp_cmdshell @STR

    An explanation of the behaviour is available at


Viewing 3 posts - 1 through 2 (of 2 total)

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