NO

Author Topic: Split SQL statements  (Read 3349 times)

Offline TimoVJL

  • Global Moderator
  • Member
  • *****
  • Posts: 2115
Split SQL statements
« on: August 05, 2011, 10:28:25 PM »
Is this enought to split SQL statements ?
Code: [Select]
#include <stdio.h>
#include <string.h>

char* SplitLineSQL(char **szSQL1, char **szSQL2)
{
char *pSQL1, *pSQL2;
int iInDlm1 = 0;
int iInDlm2 = 0;
pSQL1 = *szSQL1;
pSQL2 = *szSQL2;
do
{
while (*pSQL1 && (*pSQL1 == ' ' || *pSQL1 == '\t' || *pSQL1 == '\r' || *pSQL1 == '\n'))
pSQL1++; // cleanup whitespaces
if (*pSQL1 == '-' && *(pSQL1+1) == '-') // comment
while (*pSQL1 && *pSQL1 != '\n') pSQL1++;
if (*pSQL1 == '\r' || *pSQL1 == '\n') pSQL1++;
if (*pSQL2 == '\r' || *pSQL2 == '\n') pSQL2++;
if (*pSQL2 == '"')
{
if (!iInDlm1)
iInDlm1++;
else
iInDlm1--;
}
if (*pSQL2 == '\'')
{
if (!iInDlm2)
iInDlm2++;
else
iInDlm2--;
}
if (*pSQL2 == ';' && !iInDlm1 && !iInDlm2)
{
*pSQL2 = 0;
pSQL2++;
break;
}
pSQL2++;
} while (*pSQL2);
*szSQL1 = pSQL1;
*szSQL2 = pSQL2;
return pSQL1;
}

int main(int argc, char **argv)
{
char *pSQL1, *pSQL2;
char szTmp[1000];

char *szSQL =
"--COMMENT\r\n"
"DROP TABLE IF EXISTS test;"
"CREATE TABLE IF NOT EXISTS test (id INTEGER NOT NULL PRIMARY KEY, text VARCHAR(100));"
"INSERT INTO test VALUES (1, 'text1;'); --COMMENT2\n"
"INSERT INTO test VALUES (2, \"text1;\");"
"SELECT * FROM test;"
;

strcpy(szTmp, szSQL);
pSQL1 = szTmp;
pSQL2 = szTmp;
do {
//printf("\nSQL: [%s]\n", SplitLineSQL(&pSQL1, &pSQL2));
SplitLineSQL(&pSQL1, &pSQL2);
if (*pSQL1)
printf("SQL:[%s]\n", pSQL1);
pSQL1 = pSQL2;
} while (*pSQL2);
return 0;
}
« Last Edit: September 06, 2011, 09:21:06 AM by timovjl »
May the source be with you