Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incorrect syntax near 'GO'

How can I execute the following SQL inside a single command (single execution) through ADO.NET?

ALTER TABLE [MyTable]     ADD NewCol INT  GO  UPDATE [MyTable]      SET [NewCol] = 1 

The batch separator GO is not supported, and without it the second statement fails.

Are there any solutions to this other than using multiple command executions?

like image 855
Andrew Bullock Avatar asked Sep 05 '14 07:09

Andrew Bullock


People also ask

What is incorrect syntax near in SQL?

When executing a query in SQL and the editor throws back this error: Incorrect syntax near …'' That typically means you have used the wrong syntax for the query. This happens mostly when someone switched from one relational database to another relational database, from MySQL to MS SQL Server for example.

What is stored procedure in SQL Server?

What is a Stored Procedure? A stored procedure is a prepared SQL code that you can save, so the code can be reused over and over again. So if you have an SQL query that you write over and over again, save it as a stored procedure, and then just call it to execute it.


2 Answers

The GO keyword is not T-SQL, but a SQL Server Management Studio artifact that allows you to separate the execution of a script file in multiple batches.I.e. when you run a T-SQL script file in SSMS, the statements are run in batches separated by the GO keyword. More details can be found here: https://msdn.microsoft.com/en-us/library/ms188037.aspx

If you read that, you'll see that sqlcmd and osql do also support GO.

SQL Server doesn't understand the GO keyword. So if you need an equivalent, you need to separate and run the batches individually on your own.

like image 140
JotaBe Avatar answered Oct 10 '22 03:10

JotaBe


Remove the GO:

String sql = "ALTER TABLE  [MyTable] ADD NewCol INT;"; cmd = new SqlCommand(sql, conn); cmd.ExecuteNonQuery(); sql = "UPDATE [MyTable] SET [NewCol] = 1"; cmd = new SqlCommand(sql, conn); cmd.ExecuteNonQuery(); 

It seems that you can use the Server class for that. Here is an article:

C#: Executing batch T-SQL Scripts containing GO statements

like image 27
Tim Schmelter Avatar answered Oct 10 '22 05:10

Tim Schmelter