简体   繁体   中英

Trigger to insert NULL values (SQL Server 2012)

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:

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

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!

1) If you can change the client app (MFC) then you should do.

2) If you're using stored procedures for inserting or updating rows then you could do these transformations within these SPs. For example:

ALTER STORED PROCEDURE dbo.MyTable_Insert
(
@Slot1 INT,
@Slot2 INT,
@Slot3 INT,
@Slot4 INT
)
AS
BEGIN
SELECT @Slot1 = NULLIF(@Slot1, 0), 
    @Slot2 = NULLIF(@Slot2, 0), 
    @Slot3 = NULLIF(@Slot3, 0), 
    @Slot4 = NULLIF(@Slot4, 0);

INSERT INTO dbo.MyTable (Slot1, Slot2, Slot3, Slot4)
VALUES (@Slot1, @Slot2, @Slot3, @Slot4);
END

3) If you can't then you could use and INSTEAD OF trigger:

CREATE TRIGGER trgBeforeIU_SomeTrigger
ON dbo.MyTable
INSTEAD OF INSERT, UPDATE
AS
BEGIN
    INSERT INTO dbo.MyTable (Slot1, Slot2, Slot3, Slot4)
    SELECT  NULLIF(Slot1, 0), 
        NULLIF(Slot2, 0),
        NULLIF(Slot3, 0),
        NULLIF(Slot4, 0)
    FROM inserted;
END;

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