0

I am writing a script to extract and convert SQL statements from a file. I need to convert the sql unloaded froma gupta sqlbase database into sql that SQLServer can understand.

One task is to replace keywords that are not allowed as column names with a compatible name.

In the following code $commands is an array ref that contains sql statements. (There is actually more code here, but I extracted it because it shouldn't be relevant here)

my @KeyWords = ("LEFT", "RIGHT", "PERCENT", "FILE", "PRINT", "CROSS", "PLAN", "TOP", "END", "FILE", "Default", "CHECK", "TEXT");

foreach $cmd (@$commands) {

    foreach my $kw (@KeyWords) {
        $cmd =~ s/\b$kw\b[^(]/_$kw/gi;
    }


    push @$converted, $cmd; 
}

This works fine for most statements but in the following command "DEFAULT" gets replaced with "_DEFAULT instead of "_DEFAULT". So the second quotation mark is lost.

  CREATE TABLE SYSADM.SUBTYPE ( ID_SUBTYPE INTEGER NOT NULL, 
  ID_TYPE INTEGER NOT NULL, 
  TYPE VARCHAR(1), 
  BEZEICH VARCHAR(60), 
  NUM_COLOR INTEGER, 
  NUM_TXTCOLOR INTEGER, 
  "DEFAULT" SMALLINT, 
  GENER_ARBA SMALLINT, 
  PROJEKTPLANUNG SMALLINT)

Is there a way to modify the regular expression/substition so this will not remove the second quotation mark? Or an other way?

1 Answer 1

3

[^(] matches any single character that is not a left opening paranthesis.

You want to use a negative zero-width lookahead assertion instead:

s/\b$kw\b(?!\()/_$kw/gi;

(Alternatively: (?![(]))

You can also add the replaced character back to the string:

s/\b$kw\b([^(])/_$kw$1/gi;

But note that this will not work in all cases. Especially if there is nothing after the keyword, this pattern will not match whereas zero-width assertion will.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.