Skip to content

Instantly share code, notes, and snippets.

@booyaa
Created January 10, 2014 12:37
Show Gist options
  • Save booyaa/8351232 to your computer and use it in GitHub Desktop.
Save booyaa/8351232 to your computer and use it in GitHub Desktop.
SQL: How to replace an old id with new value
/*
Assume you have a value in a table that looks like this:
select foo from bar
|foo |
|uspFTW 123|
You want to change 123 to 929
*/
declare @newid as varchar(3);
declare @oldid as varchar(3);
set @newid=929 -- this could easily be integrated into a sqlcmd script by replacing 929 with $(newid)
--grab old id (assumes id is on the right most and is only 3 chars long, tailor accordnigly)
select @oldid=right(rtrim(ltrim(foo)),3) from bar
--boom!
select replace(foo, @oldid, @newid) as newFoo, foo as oldFoo from bar
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment