I am trying to create a trigger with SqlCommand
and I am getting the error:
Incorrect syntax near the keyword 'trigger'
When I copy the same query in SQL Server it is executing successfully.
Here is how the SQL command looks like.
command.CommandText = "CREATE TRIGGER tr_Korisnik" + korisnik.KorisnikID + "_FakturaStavka_ForInsert " +
"on Korisnik"+korisnik.KorisnikID+"_FakturaStavka " +
"FOR INSERT " +
"AS " +
"BEGIN " +
"DECLARE @ID int " +
"DECLARE @FakturaID int " +
"DECLARE @StavkaBr int " +
"SET @ID = (SELECT DokumentID from inserted) " +
"SET @FakturaID = (SELECT FakturaID from inserted) " +
"UPDATE Korisnik"+korisnik.KorisnikID+"_Fakturi SET BrStavki = BrStavki+1 WHERE DokumentID = @FakturaID " +
"SET @StavkaBr = (SELECT Korisnik"+korisnik.KorisnikID+"_Fakturi.BrStavki FROM Korisnik"+korisnik.KorisnikID+"_Fakturi WHERE DokumentID = @FakturaID) " +
"UPDATE Korisnik"+korisnik.KorisnikID+"_FakturaStavka SET StavkaBroj = @StavkaBr WHERE DokumentID = @ID END";
command.ExecuteNonQuery();
Also, above that I have SQLCommands for CREATE TABLE
and they work properly.
I tried USE [databasename]
before CREATE TRIGGER
, still nothing.
I removed the concatenations +"korisnik.KorisnikID"
and made clean names, still can't execute it.
The documentation for ExecuteNonQuery states that
Which sort of confirms my suspicions: you can't create a trigger this way.
If you want to create a trigger in code, use a CLR Trigger.