简体   繁体   中英

“Incorrect syntax near 'GO'” when inserting values

I'm getting the error above. I use this code:

  //split the script on "GO" commands
                string[] splitter = new string[] { "\r\nGO\r\n" };
                string[] commandTexts = data.Split(splitter,
                  StringSplitOptions.RemoveEmptyEntries);

  foreach (string commandText in commandTexts)
  {
    SqlCommand cmdScript = new SqlCommand(commandText, conn);
    cmdScript.ExecuteNonQuery();               
   }

I scripted the content of my tables with the SSMS so I got a file with lots of 'INSERT INTO' Statements and some 'GO' Statements between them.

The last 'GO' statement isn't at the end of the file - after the last statement there are a few 'INSERT INTO' lines. This works fine when executing it in SSMS but not in C# with the construct above.

I put a counter in to count the amount of 'commandText' int the loop. I had 3107. After I added a 'GO' at the end of the file, my counter shows 3108 and still get the error. In both cases all data gets completely inserted into my tables, so the error happens at the end. Any idead what this could be?

如果改用字符串生成器会更容易。可以使用字符串builder.append类添加新的字符串行

If the parser say 'syntax error before GO' it means you sent the GO to the server. It must be that your splitter does not correctly split. Is likely something like a space after the GO, making it not match the \\r\\nGO\\r\\n exactly.

You can give https://github.com/rusanu/DbUtilSqlCmd a try.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM