T-SQL How to create function that comapres string, checks difference, and do special function : First - sorry for my english. Second - i'm learning t-SQL.


----------


**Goal:**


I want to get difference between two strings, then check in which column is this difference. If the difference is in first column, do something, if in second column - do something else.


----------


**What I'm actually doing**

Column 'messages' is a string which contains list of ID. So i am replacing all '#' with ',' and deleting last ',' what gives to me **ActualID** and **BeforeID** column. See below:

    DECLARE @string VARCHAR(512);
    DECLARE @string2 VARCHAR(512);
    DECLARE @string3 VARCHAR(512);

    SET @string = '41#42#43#44#45#46#47#48#49#50#51#52#53#54#55#56#57#58#59#';
    SET @string2 = REPLACE((SELECT messages FROM USERS WHERE userid = 4), '#', ', ' )
    SET @string3 = left(@string2, len(@string2) - 1);
    SET @string2 = REPLACE(@string, '#', ', ' )
    SET @string = left(@string2, len(@string2) - 1);
    SELECT @string3 as ActualID, @string as BeforeID
[![myquery][1]][1]


  [1]: https://i.stack.imgur.com/6nLDR.png


----------


So now, I want compare **BeforeID** with **ActualID**. For example: 

In BeforeID we have `1, 2, 3` / In **ActualID** `1, 2, 3, 4` 

In example above `4` was added. So, if it was added I want to add it to `@AddedElements`. 

If `4, 5, 7` were added then `SELECT @AddedElements as AddedElements` should return `4, 5, 7` (With comas)

But, that's not all.

If **BeforeID** = `1, 5, 10, 14` and **ActualID** = `1, 5, 14` I want, that element which is in **BeforeID**, but not in **AcutalID** will be added to @DeletedElements. 

So `SELECT @DeletedElements as DeletedElements` should return `10`


Added elements/Deleted elements should be returned once. I mean, full result what I want to Earn should be

`SELECT @AddedElements as AddedElements, @DeletedElements as DeletedElements`


----------

Is it possible? If, then how to do it?



 