I am running some SQL that identifies records which need to be marked for deletion and to insert a value into those records. This value must be changed to render the record useless and each record must be changed to a unique value because of a database constraint.
UPDATE Users
SET Username = 'Deleted' + (ISNULL(
Cast(SELECT RIGHT(MAX(Username),1)
FROM Users WHERE Username LIKE 'Deleted%') AS INT)
,0) + 1
FROM Users a LEFT OUTER JOIN #ADUSERS b ON
a.Username = 'AVSOMPOL\' + b.sAMAccountName
WHERE (b.sAMAccountName is NULL
AND a.Username LIKE 'AVSOMPOL%') OR b.userAccountControl = 514
This is the important bit:
SET Username = 'Deleted' + (ISNULL(
Cast(SELECT RIGHT(MAX(Username),1)
FROM Users WHERE Username LIKE 'Deleted%') AS INT)
,0) + 1
What I've tried to do is have deleted records have their Username field set to 'Deletedxxx'. The ISNULL is needed because there may be no records matching the SELECT RIGHT(MAX(Username),1) FROM Users WHERE Username LIKE 'Deleted%'
statement and this will return NULL
.
I get a syntax error when trying to parse this (Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'SELECT'.
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near ')'.
I'm sure there must be a better way to go about this, any ideas?