/ Published in: SQL
Stored Procedure for search and replace a string in all fields of all tables of one DataBase
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
CREATE Proc SearchAndReplace ( @SearchStr nVarChar(100), @ReplaceStr nVarChar(100) ) AS BEGIN SET NoCount ON DECLARE @TableName nVarChar(256), @ColumnName nVarChar(128), @SearchStr2 nVarChar(110), @SQL nVarChar(4000), @RCTR INT SET @TableName = '' SET @SearchStr2 = QuoteName('%' + @SearchStr + '%','''') SET @RCTR = 0 While @TableName IS NOT NULL BEGIN SET @ColumnName = '' SET @TableName = ( SELECT MIN(QuoteName(TABLE_SCHEMA) + '.' + QuoteName(TABLE_NAME)) FROM INFORMATION_SCHEMA.Tables WHERE Table_TYPE = 'BASE Table' AND QuoteName(TABLE_SCHEMA) + '.' + QuoteName(TABLE_NAME) > @TableName AND ObjectProperty ( Object_Id(QuoteName(TABLE_SCHEMA) + '.' + QuoteName(TABLE_NAME)), 'IsMSShipped' ) = 0 ) While (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL) BEGIN SET @ColumnName = ( SELECT MIN(QuoteName(COLUMN_NAME)) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2) AND TABLE_NAME = PARSENAME(@TableName, 1) AND DATA_TYPE IN ('char', 'VarChar', 'nchar', 'nVarChar') AND QuoteName(COLUMN_NAME) > @ColumnName ) IF @ColumnName IS NOT NULL BEGIN SET @SQL = 'Update ' + @TableName + ' Set ' + @ColumnName + ' = ' + 'Replace(' + @ColumnName + ', ' + QuoteName(@SearchStr, '''') + ', ' + QuoteName(@ReplaceStr, '''') + ') ' + 'Where ' + @ColumnName + ' Like ' + @SearchStr2 EXEC (@SQL) SET @RCTR = @RCTR + @@ROWCOUNT END END END SELECT 'Replaced ' + CAST(@RCTR AS VARCHAR) + ' occurence(s)' AS 'Outcome' END