I need a SQL trigger that would zero pad a cell whenever its inserted or updated. Was curious if its best practice to append two strings together like I’m doing in the update command. Is this be best way to do it?
CREATE TRIGGER PadColumnTenCharsInserted ON Table
AFTER INSERT
AS
DECLARE
@pad_characters VARCHAR(10),
@target_column NVARCHAR(255)
SET @pad_characters = '0000000000'
SET @target_column = 'IndexField1'
IF UPDATE(IndexField1)
BEGIN
UPDATE Table
SET IndexField1 = RIGHT(@pad_characters + IndexField1, 10)
END
GO
Your padding code looks fine.
Instead of updating every row in the table like this:
update just the row that triggered the trigger:
Also, you’ve still got some extraneous code — everything involving @target_column. And it looks like you’re not sure if this is an INSERT trigger or an UPDATE trigger. I see
AFTER INSERTandIF UPDATE.