所有数据库中的SQL搜索和替换
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了所有数据库中的SQL搜索和替换相关的知识,希望对你有一定的参考价值。
Stored Procedure for search and replace a string in all fields of all tables of one DataBase
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
以上是关于所有数据库中的SQL搜索和替换的主要内容,如果未能解决你的问题,请参考以下文章