1

I am tring to insert into two tables but something goes wrong. It returns this message:

Additional information: Incorrect syntax near 'GO'.

con.Open();
SqlCommand cmd = new SqlCommand("SET IDENTITY_INSERT dbo.Tomasos ON;GO DECLARE @IDENTITY INT INSERT INTO Bestallning (BestallningDatum, Totalbelopp, Levererad, KundID) VALUES ('28-02-2014', '250', '1', '1') SELECT @IDENTITY = SCOPE_IDENTITY() INSERT INTO BestallningMatratt (MatrattID, BestallningID, Antal) VALUES ('1', @IDENTITY, '3') SET IDENTITY_INSERT dbo.Tomasos OFF; GO", con);
cmd.ExecuteNonQuery();
con.Close();
Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275
G.D
  • 181
  • 7

2 Answers2

2
SET IDENTITY_INSERT dbo.Tomasos ON;

DECLARE @IDENTITY INT INSERT INTO Bestallning (BestallningDatum, Totalbelopp, Levererad, KundID) VALUES ('28-02-2014', '250', '1', '1')
SELECT @IDENTITY = SCOPE_IDENTITY()
INSERT INTO BestallningMatratt (MatrattID, BestallningID, Antal) VALUES ('1', @IDENTITY, '3') SET IDENTITY_INSERT dbo.Tomasos OFF;

I dont think you need the GO at the end i also think you need

SET IDENTITY_INSERT dbo.Tomasos OFF;

P6345uk
  • 703
  • 10
  • 26
  • duplicate here http://stackoverflow.com/questions/18596876/go-statements-blowing-up-sql-execution-in-net – P6345uk Nov 16 '15 at 11:51
2

go is a batch separator and here you don't have commands that need to be executed separately, thus you can do it as a single batch:

con.Open();
SqlCommand cmd = new SqlCommand(@"SET IDENTITY_INSERT dbo.Tomasos ON;
DECLARE @IDENTITY INT;
INSERT INTO Bestallning 
  (BestallningDatum, Totalbelopp, Levererad, KundID) 
  VALUES 
  ('28-02-2014', '250', '1', '1');

SELECT @IDENTITY = SCOPE_IDENTITY();
INSERT INTO BestallningMatratt 
  (MatrattID, BestallningID, Antal) 
  VALUES 
  ('1', @IDENTITY, '3');
SET IDENTITY_INSERT dbo.Tomasos OFF;", con);
cmd.ExecuteNonQuery();
con.Close();

EDIT: BTW looking at the values and field names, it sounds like some of the values are not strings in fact but you are relying on implicit conversion which is very dangerous. Since you are using C#, it would be much easier and safer to pass real values with real datatypes as parameters instead (and in real life nobody would harcode the values anyway).

Cetin Basoz
  • 22,495
  • 3
  • 31
  • 39