Technical Article

Find and Replace a value across all tables in database

,

1. Copy and Paste the script.

2. Update the values

@SearchThis='goodmorning'
@ReplaceWith='good morning'
3.Execute the script. 
Begin

Set NOCount on
SET ANSI_WARNINGS  OFF


Declare @TotalRec int
Declare @Count int
Declare @TableName varchar(256)
Declare @ColumnName varchar(256)
Declare @RowNum int
Declare @SqlScript varchar(999)
Declare @SearchThis nvarchar(256)
Declare @ReplaceWith nvarchar(256)

Set @SearchThis='goodmorning'
Set @ReplaceWith='good morning'

Declare  @TableColumn Table
(
RowNum int Identity(1,1),
TableName varchar(256),
ColumnName varchar(256)
)

Create Table #TableColumn1
(
RowNum int Identity(1,1),
TableName varchar(256),
ColumnName varchar(256)
)

Insert into @TableColumn


select distinct T.TABLE_NAME --as 'TableName'
,Col.COLUMN_NAME --as 'ColumnName'
from
INFORMATION_SCHEMA.COLUMNS Col with (nolock)
inner join INFORMATION_SCHEMA.TABLES T  with (nolock) on T.TABLE_NAME=Col.TABLE_NAME and T.TABLE_TYPE='BASE TABLE'
where  DATA_TYPE IN ('char', 'varchar', 'nchar', 'nVarChar','text')  and T.TABLE_SCHEMA='dbo' and T.TABLE_TYPE='BASE TABLE'

Set @TotalRec=(select count(*) from @TableColumn)
Set @Count=0

while @TotalRec>@Count
Begin

Set @Count=@Count+1
Set @TableName=(Select top 1 TableName From @TableColumn T where T.RowNum=@Count)
Set @ColumnName=(Select top 1 ColumnName From @TableColumn T where T.RowNum=@Count)
 Begin Try
 EXEC ( 'Update '+@TableName+ ' Set '+ @ColumnName+'='+''''+@ReplaceWith+''''+ ' Where '+@ColumnName+' = '+''''+@SearchThis+'''')
         End Try
         Begin catch

         End catch
End

Drop table #TableColumn1
SET ANSI_WARNINGS ON;


End

Rate

3.11 (9)

You rated this post out of 5. Change rating

Share

Share

Rate

3.11 (9)

You rated this post out of 5. Change rating