In SQL Server sometimes we get some data for which we are not sure that from which table it is coming the we can use the below stored procedure to find it.
It has 3 input parameters:
- @DataToSearch: Data which you want to search.
- @DataToReplace: Data with which you want to replace.
- @IsExactMatch: Search for exact matching or search any mathing data. If you want to search any matching data you can leave it blank.
This stored procedure does not alter any value in database it only displays the list of table with column name which have the specified data. the @DataToReplace has value the it will show you an script to replace the value which you need to execute separately.
- CREATE PROCEDURE FindAnyStringFromTheDataBase
- @DataToSearch NVARCHAR(4000),
- @DataToReplace NVARCHAR(4000),
- @IsExactMatch BIT = 0
- AS
- SET NOCOUNT ON
-
- DECLARE @TempTable TABLE(RowId INT IDENTITY(1,1), SchemaName sysname, TableName sysname, ColumnName SysName, DataType VARCHAR(100), IsDataFound BIT)
-
- INSERT INTO @TempTable(TableName,SchemaName, ColumnName, DataType)
- SELECT Col.Table_Name,Col.TABLE_SCHEMA, Col.Column_Name, Col.Data_Type
- FROM Information_Schema.Columns AS Col
- INNER Join Information_Schema.Tables AS Tbl
- ON Col.Table_Name = Tbl.Table_Name
- AND Col.TABLE_SCHEMA = Tbl.TABLE_SCHEMA
- WHERE Table_Type = 'Base Table'
- And Data_Type In ('ntext','text','nvarchar','nchar','varchar','char')
-
-
- DECLARE @i INT
- DECLARE @MAXValue INT
- DECLARE @TableName sysname
- DECLARE @ColumnName sysname
- DECLARE @SchemaName sysname
- DECLARE @SQL NVARCHAR(4000)
- DECLARE @PARAMETERS NVARCHAR(4000)
- DECLARE @IsDataExists BIT
- DECLARE @SQLTemplate NVARCHAR(4000)
- DECLARE @dbName VARCHAR(100)
-
- SELECT @SQLTemplate = CASE WHEN @IsExactMatch = 1
- THEN 'If Exists(Select *
- From ReplaceTableName
- Where Convert(nVarChar(4000), [ReplaceColumnName])
- = ''' + @DataToSearch + '''
- )
- Set @IsDataExists = 1
- Else
- Set @IsDataExists = 0'
- ELSE 'If Exists(Select *
- From ReplaceTableName
- Where Convert(nVarChar(4000), [ReplaceColumnName])
- Like ''%' + @DataToSearch + '%''
- )
- Set @IsDataExists = 1
- Else
- Set @IsDataExists = 0'
- END,
- @PARAMETERS = '@IsDataExists Bit OUTPUT',
- @i = 1
-
- SELECT @i = 1, @MAXValue = MAX(RowId)
- FROM @TempTable
-
- WHILE @i <= @MAXValue
- BEGIN
- SELECT @SQL = REPLACE(REPLACE(@SQLTemplate, 'ReplaceTableName', QUOTENAME(SchemaName) + '.' + QUOTENAME(TableName)), 'ReplaceColumnName', ColumnName)
- FROM @TempTable
- WHERE RowId = @i
-
-
- PRINT @SQL
- EXEC SP_EXECUTESQL @SQL, @PARAMETERS, @IsDataExists = @IsDataExists OUTPUT
-
- IF @IsDataExists =1
- UPDATE @TempTable SET IsDataFound = 1 WHERE RowId = @i
-
- SET @i = @i + 1
- END
-
- SET @dbName = DB_NAME()
-
- SELECT SchemaName,@dbName as DB,TableName, ColumnName,
- 'Update '+ @dbName+'.'+SchemaName+'.'+TableName+ ' SET '+ColumnName+ ' = replace('+ColumnName+','''+ @DataToSearch+''','''+@DataToReplace+''')' as Script
- FROM @TempTable
- WHERE IsDataFound = 1
-
- GO