Search code examples
sql-servert-sqltransactions

UPDATE table during SELECT?


I'm trying to do this all in T-SQL.

Table1 contains:

somename nvarchar(255);

This is the general idea of what I want to do... "somename" field contains a string of characters. That string of characters is SOMETIMES appended with another string sequence like "abc123". Sometimes it is not. With as few SQL lines as possible, I would like to update the somename field in all records that END in "abc123" and the updated value would be whatever the value was before, MINUS the "abc123" part.

Sort of an example:

select IP_Address,Caption,LEN(Caption) as xlength from Nodes
where right(Caption,18)='.somedomain.com';
update Nodes SET Caption=LEFT(Caption,(xlength-15));

15 being, of course, the length of the string ".somedomain.com"

This doesn't work of course, but it should give you an idea of what I'm trying to accomplish.


Solution

  • You are on right track. A query like below will suffice:

    DECLARE @seq Nvarchar(max) ='abc123'
    
    UPDATE yourtable
    SET somename = LEFT(somename,LEN(Somename)-LEN(@seq))
    WHERE somename like '%' + @seq