Home Forums SQL Server 2005 T-SQL (SS2K5) trying to export to .CSV with comma delimited AND double-quotes RE: trying to export to .CSV with comma delimited AND double-quotes

  • This will do it.

    bcp "SELECT QUOTENAME('Address',CHAR(34))+','+QUOTENAME('City',CHAR(34))+','+QUOTENAME('State',CHAR(34))+','+QUOTENAME('ZIP',CHAR(34)) d UNION ALL SELECT QUOTENAME(AddressLine1,CHAR(34))+',' + QUOTENAME(City,CHAR(34))+',' + QUOTENAME(StateProvinceID,CHAR(34))+',' + QUOTENAME(PostalCode,CHAR(34)) FROM AdventureWorks.Person.Address" queryout "C:\Temp\Contacts.txt" -c -T -SPutYourServer\InstanceNameHere

    Change the "PutYourServer\InstanceNameHere" to the actual name of you Server and Instance name. This particular code runs against the AdventureWorks database. You'll need to change the FROM clause for that and the column names to match the table you're drawing from.

    This code also writes to "C:\Temp\Contacts.txt" on the server. You can change that to whatever UNC you want.

    Last but not least, this uses a Trusted Conection with Windows Authentication. If you only have SQL Server Authentication, then I don't recommend using this because you'll need to include the user name and password in clear text. Instead, you'd need to use %1 and %2 as batch substitution variables in a batch file and provide them at run time.

    If your system is properly locked down for it, you could to this from a stored procedure using xp_CmdShell in a stored procedure or just from a job on the server.

    --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)