1

Is there a way to scan all tables in MS SQL 2008 R2 Database and replace one word to another? Or if replace is not possible maybe just possibility to list all rows with specific word (and corresponding table next to it for reference)?

If it's not possible to do purely in SQL then I can use C# as well.

1 Answer 1

1

There is no "out of the box" solution for this, but it's not very hard to write a stored procedure that does this.

For example, the procedure below will loop over all the tables and then loop over all the columns of type varchar and nvarchar and replace the string @value with @newvalue. This is just a proof of concept and can be enhanced greatly to make it faster by adding a where clause that checks if the string contains the value for example. (with LIKE or using full text indexes).

create proc ReplaceStrings(
        @value nvarchar(maX)
      , @newvalue nvarchar(max)
      )
AS
declare @table_id int
      , @name sysname
      , @fieldname sysname
      , @sql nvarchar(max)
      , @fields nvarchar(max)

if @value = ''
  begin
      raiserror('The search value can not be empty', 16, 1) 
      return (-1)
  end    
declare tab cursor read_only local
for
select object_id, name from sys.tables

open tab
fetch next from tab into @table_id, @name

while @@FETCH_STATUS = 0 
  begin

    SELECT @sql = N'UPDATE ' + QUOTENAME(@name) + ' 
                set '  
         , @fields = NULL
    declare field cursor read_only local
    for 
    select name from sys.columns where object_id = @table_id and system_type_id in (type_id('varchar'), type_id('nvarchar'))
    open field
    fetch next from field into @fieldname
    while @@FETCH_STATUS = 0
      begin
        set @fields = coalesce(@fields + ',', '') + N' ' + quotename(@fieldname) + '  = REPLACE(' + quotename(@fieldname) + ', @value, @newvalue)' 
        fetch next from field into @fieldname        
      end
    close field
    deallocate field

    set @sql += @fields 

    print @sql
    exec sp_executesql @sql , N'@value nvarchar(max), @newvalue nvarchar(max)', @value, @newvalue

    fetch next from tab into @table_id, @name
  end
close tab
deallocate tab

return (0)

Call the procedure like this:

exec ReplaceStrings 'haha', 'hihi'
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. This seems like a good way to do it. I will test it out. Really appreciate code example!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.