• You have single quotes around variables names. The RED plus signs are the give-away. You also had a scad of double quotes in the wrong places and you don't actually need the full path to BCP... it should be part of the Environment Path Variable.

    There are also other things wrong with the BCP command. For example, if you specify the "-T" option (Trusted Connection), there is no need to use a user name or password. SQL Server will take care of it.

    You also have to specifiy the 3 part naming convention for your table names.

    To make life easier in the future, you need to make and test a BCP command with no variables at all. Once you have it working, then you can easily convert it to dynamic SQL using what I call "Dynamic SQL for the DBA". The whole idea is simply to take a known good BCP command, tokenize it for variables and the like, "Slosh" it for readability, and you're done.

    Of course, there's also such a thing as "DOS INJECTION" and you really need to build a function to test the variables with to make sure that things like "&" and "&&" (DOS Command "stringing") don't show up in your final concatenated or tokenized code.

    Here's what I came up with...

    SELECT @Command = REPLACE(REPLACE(REPLACE(REPLACE('BCP "SELECT DocData FROM dbnamehere.schemanamehere.table WHERE DocId = <<@DocID>>" queryout "C:\user\<<@DocId>>_<<@FileName>>.<<@FileExtension>>" -S<<@@SERVERNAME>> -T -c -CRAW'

    ,'<<@DocID>>' ,CONVERT(VARCHAR(10),@DocID))

    ,'<<@FileName>>' ,@FileName)

    ,'<<@FileExtension>>',@FileExtension)

    ,'<<@@SERVERNAME>>' ,@@SERVERNAME)

    ;

    Notice that all the difficulty with getting single quotes right and all the plus signs, etc, has simply vanished thanks to the tokenization of the command.

    And, no... "Slosh" is not a term I made up. Look it up in Books Online by looking up the "\ (backslash)" character without the quotes. 😀 Even though it's not documented in versions earlier than 2008, it still works at least as far back as 2005. And, the version of BOL 2008 that comes with SQL Server 2008 disks is the ONLY place in any of the BOLs that I've seen where you can actually search for the word "slosh" and it takes you to the "\ (backslash)" section.

    Here's the 2014 versio from the internet.

    http://msdn.microsoft.com/en-us/library/dd207007.aspx

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)