title: Trigger to insert NULL values (SQL Server 2012)
body: <p>Some days ago I was developing an MFC Application which works as a client for a database of mine. In this application, there are some situations that some fields of a new record may be empty, which would represent a "zero" (null) when I fill some of the objects with data. So, in order to deal with these zero values, I was trying to create a trigger that would automatically substitute these zero values for a NULL, and so there wouldn't be any foreing key conflicts. Here is what I've implemented so far:</p>
  
  <pre><code>use SomeDatabase SET ANSI_NULLS ON
  GO
  SET QUOTED_IDENTIFIER ON
  GO
  create trigger SomeTrigger
  on MyTable
  after insert, update
  as
  begin
  declare @Attribute1 int
  declare @Attribute2 int
  declare @Attribute3 int
  declare @Attribute4 int
  set @Attribute1 = (select Slot1 from INSERTED)
  set @Attribute2 = (select Slot2 from INSERTED)
  set @Attribute3 = (select Slot3 from INSERTED)
  set @Attribute4 = (select Slot4 from INSERTED)
  if (@Attribute1 = 0)
  begin TRANSACTION
  SET Slot1 NULL
  end
  if (@Attribute2 = 0)
  begin TRANSACTION
  SET Slot2 NULL
  end
  if(@Attribute3 = 0)
  begin TRANSACTION
  SET Slot3 NULL
  end
  if (@Attribute4 = 0)
  begin TRANSACTION
  SET Slot4 NULL
  end
  end
  go
  </code></pre>
  
  <p>I am pretty sure there are better ways than this one, but I believe that the most curious thing is that SQL Server is accusing errors only at the last 2 "if's", and the last "end" and "go". Does anyone knows a better solution for this? Thanks in advance!</p>