To bulk copy out the result set of a SELECT statement
When using these steps the file is created in native format. You can convert the data values to other data types by using bcp_colfmt, for more information, see the How to create a bulk copy format file (ODBC) section.
The following example shows using bulk copy functions to bulk copy out the result set of a SELECT statement. Most error-checking code is removed to simplify this example.
// Sample showing ODBC BCP_OUT of a SELECT result set
// using native mode format.
#include <stdio.h>
#include <string.h>
#include <windows.h>
#include <sql.h>
#include <sqlext.h>
#include <odbcss.h>
SQLHENV      henv = SQL_NULL_HENV;
HDBC         hdbc1 = SQL_NULL_HDBC;
int main() {
   RETCODE retcode;
   // Bulk copy variables.
   SDWORD   cRows;
   SQLTCHAR   szBCPQuery[] =
      "SELECT LastName, FirstName FROM Northwind.dbo.Employees";
    // Allocate the ODBC environment and save handle.
   retcode = SQLAllocHandle (SQL_HANDLE_ENV, NULL, &henv);
   // Notify ODBC that this is an ODBC 3.0 app.
   retcode = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION,
                     (SQLPOINTER) SQL_OV_ODBC3,
                      SQL_IS_INTEGER);
   // Allocate ODBC connection handle, set bulk copy mode, and 
   // then connect.
   retcode = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc1);
   retcode = SQLSetConnectAttr(hdbc1, SQL_COPT_SS_BCP,
                        (void *)SQL_BCP_ON,
                         SQL_IS_INTEGER);
   retcode = SQLConnect(hdbc1, "MyDSN", SQL_NTS,
            "sa", SQL_NTS, "MyPassWord", SQL_NTS);
   
   // Initialize the bulk copy.
   retcode = bcp_init(hdbc1, NULL, "c:\\BCPODBC.bcp",
                  "c:\\BCPERROR.out, DB_OUT);
   // Note that the test is for the bulk copy return of SUCCEED,
   // not the ODBC return of SQL_SUCCESS.
   if ( (retcode != SUCCEED) )
   {
         ProcessLogMessages(SQL_HANDLE_DBC, hdbc1,
                     "bcp_init(hdbc1) Failed\n\n");
         return(9);
   }
   // Specify the query to use.
   retcode = bcp_control(hdbc1, BCPHINTS, (void *)szBCPQuery);
   if ( (retcode != SUCCEED) )
   {
         ProcessLogMessages(SQL_HANDLE_DBC, hdbc1,
                     "bcp_control(hdbc1) Failed\n\n");
         return(9);
   }
   // Execute the bulk copy.
   retcode = bcp_exec(hdbc1, &cRows);
   if ( (retcode != SUCCEED) )
   {
         ProcessLogMessages(SQL_HANDLE_DBC, hdbc1,
                     "bcp_exec(hdbc1) Failed\n\n");
         return(9);
   }
   printf("Number of rows bulk copied out = %d.\n", cRows);
   /* Clean up. */
   SQLDisconnect(hdbc1);
   SQLFreeHandle(SQL_HANDLE_DBC, hdbc1);
   SQLFreeHandle(SQL_HANDLE_ENV, henv);
   return(0);
}