Friday, March 23, 2012

Replace NULL with "-" using Trigger

Can a Trigger be created to automatically replace NULL values with "-"? Suppose I have an Entry Form with 20 Text Boxes. I don't want to code in my application. I want that when an Insert Query is executed, a BEFORE/AFTER TRIGGER should be executed to replace the NULL values coming from Insert QUery to "-".

I also want to know whether to use a Trigger or a Function/Stored Procedure.

I'd simply add the logic to your T-SQL insert statement with the ISNULL function. If its wrapped in a stored procedure it may look like something like the following:-

Code Snippet

CREATE PROC Test

@.Var1 CHAR(1),

@.Var2 CHAR(1)

AS

INSERT INTO YourTable (Var1, Var2)

VALUES ( ISNULL(@.Var1, '-'), ISNULL(@.Var2, '-') )

Using an INSTEAD OF trigger may be possible but that would seem a little over complicated for this.

HTH!

No comments:

Post a Comment