Good morning,
I'm new to Triggers and am not understanding why this is not working. I've tried the web and none of the articles seem to answer my question. What I'm trying to do is clean a string and standardize some data the users input into a 1000 character varchar field. I have a source table which has a trigger on it that inserts a limited number of columns that we'll use for reporting purposes. After the row has been inserted into the table (referred to as "destination" in the code block), I'm looking to update the comments string, capitalizing the first character of the string, standardizing spacing after a colon, removing hyphens at the beginning of the string. The source and destination tables both have the comments field as a varchar 1000, not null data type with a key id between the source and destination tables. At another segment of our system, there were errors reporting nulls and when this was removed, everything cleared up. I can do a series of replace statements when the data is required in reports but would rather have it clean in the destination table. The code is below:
CREATE TRIGGER [dbo].[destination_Update_trg] ON [dbo].[destination] AFTER UPDATE AS BEGIN SET NOCOUNT ON; IF EXISTS (SELECT * FROM destination C JOIN INSERTED I ON I.PrimaryKeyID = C.PrimaryKey WHERE I.Comments IS NOT NULL AND I.Comments <> '') BEGIN UPDATE T SET T.Comments = CASE WHEN T.Comments <> '' AND LEFT(CAST(T.Comments AS VARCHAR (1000)), 2) LIKE '- %' THEN SUBSTRING(T.Comments, 3, 1000) END FROM destination T JOIN INSERTED I ON T.primarykey = I.primarykey WHERE T.primarykey = I.primarykey UPDATE T SET T.Comments = UPPER(LEFT(CAST(T.Comments AS VARCHAR (1000)), 1)) + SUBSTRING(CAST(T.Comments AS VARCHAR (1000)), 2, 1000) FROM destination T JOIN INSERTED I ON T.primarykey = I.primarykey WHERE T.primarykey = I.primarykey UPDATE T SET T.Comments = REPLACE(SUBSTRING(T.Comments, 1, 1000), ': ', ': ')-- '[A-9]: [A-9]' FROM destination T JOIN INSERTED I ON T.primarykey = I.primarykey WHERE T.primarykey = I.primarykey AND SUBSTRING(T.Comments, 1, 1000) LIKE '%[A-Z]%: [A-Z]%' END RETURN END; GOPerhaps there's a better way to accomplish the task. I appreciate your review and assistance. Thank you.