Search code examples
c++sqlcreate-table

Excute create table in SQL Server with C++


I am trying to create a table in SQL Server with following code:

#include <iostream>
#include <windows.h>
#include <string>
#include <sql.h>
#include <sqltypes.h>
#include <sqlext.h>
using namespace std;

void main()
{
    SQLHANDLE sqlevent, sqlconnection, sqlstatement;

    SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &sqlevent);

    SQLSetEnvAttr(sqlevent, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0);

    SQLAllocHandle(SQL_HANDLE_DBC, sqlevent, &sqlconnection);

    SQLCHAR retstring[10000];
    SQLDriverConnect(sqlconnection, NULL, (SQLCHAR*)("DRIVER={SQL Server Native Client 10.0};SERVER=SERVER;DATABASE=DATABASE;UID=CrystalReports;PWD=PASSWORD"), SQL_NTS, retstring, 10000, NULL, SQL_DRIVER_NOPROMPT);  

    SQLAllocHandle(SQL_HANDLE_STMT, sqlconnection, &sqlstatement);

    string commandline;

    commandline = "CREATE TABLE NEW_TABLE01(Name VARCHAR(10), Age INT, Salary DOUBLE PRECISSION)";

    if(SQL_SUCCESS != SQLExecDirect(sqlstatement, (SQLCHAR*)(commandline.c_str()), SQL_NTS))    // SQLExecDirect always failed to excute
    {
        cout<<"The create table sql command hasn't been excuted successfully."<<endl;
        return;
    }
    return;
}

However, the code if(SQL_SUCCESS != SQLExecDirect(sqlstatement, (SQLCHAR*)(commandline.c_str()), SQL_NTS)) always return a TRUE, which means the SQL command was not sucessfully excuted.

I've got all the permission to create a table, and I've check the SQL command in SQL server manually, and it works.

May I know what am I wrong? And how can I achieve my goal?

Many thanks in advance.


Solution

  • I think I've got answer since inspired by C++ SQL Database program

    I realised that there are different schemas in SQL Server, thus I use CREATE TABLE [ROU].[NEW_TABLE01] instead. Now my code works well.