use BANCO
set nocount on
go
Declare @lookfor varchar (8000)
DECLARE @replaceby VARCHAR (8000)
— ATENÇÃO!!! ESTES SÃO OS PARÂMETROS PARA SEARCH/REPLACE
SET @lookfor = ‘DE’
SET @replaceby = ‘PARA’
–SET @replaceby = NULL — substituir pelo valor do replace, se = NULL a Query só pesquisa.
–drop table ##wrk
IF OBJECT_ID (‘TempDB..##wrk’) IS not NULL drop table ##wrk
create table ##wrk(
qtde int,
tblName varchar( 255),
colName varchar( 255),
query varchar(4000 )
)
declare cCursor cursor local fast_forward for
select tbl. name as tblName , col. name as colName , typ. name AS typeName
from
sysobjects tbl
inner join(
syscolumns col
inner join systypes typ
on typ. xtype = col .xtype
)
on col. id = tbl .id
where tbl. xtype = ‘U’
and typ .name in( ‘varchar’, ‘nvarchar’, ‘text’, ‘ntext’)
and tbl .name not in(‘SiteLog’ )
—
declare @tblName varchar (255)
declare @colName varchar (255)
DECLARE @typeName VARCHAR (255)
—
declare @sql nvarchar (4000)
declare @crlf char (2)
set @crlf = char( 13) + char (10)
open cCursor
fetch cCursor into @tblName, @colName , @typeName
while @@fetch_status = 0
begin
set @sql = ”
set @sql = @sql + ‘declare @found bit’ + @crlf
set @sql = @sql + ” + @crlf
set @sql = @sql + ‘set @found = case when exists(‘ + @crlf
set @sql = @sql + ‘ select 1’ + @crlf
set @sql = @sql + ‘ from [‘ + @tblName + ‘]’ + @crlf
set @sql = @sql + ‘ where [‘ + @colName + ‘] like ”%” + @lookfor + ”%”’ + @crlf
set @sql = @sql + ‘ ) then 1’ + @crlf
set @sql = @sql + ‘ else 0’ + @crlf
set @sql = @sql + ‘ end’ + @crlf
set @sql = @sql + ‘if @found = 1’ + @crlf
set @sql = @sql + ‘begin’ + @crlf
set @sql = @sql + ‘ insert into ##wrk’ + @crlf
set @sql = @sql + ‘ select count(*), @tblName, @colName, ”select * from [‘ + @tblName + ‘] where [‘ + @colName + ‘] like ””%” + @lookfor + ”%”””’ + @crlf
set @sql = @sql + ‘ from [‘ + @tblName + ‘]’ + @crlf
set @sql = @sql + ‘ where [‘ + @colName + ‘] like ”%” + @lookfor + ”%”’ + @crlf
IF @replaceby IS NOT NULL
BEGIN
IF @typeName IN( ‘text’, ‘ntext’)
BEGIN
set @sql = @sql + ‘ update [‘ + @tblName + ‘]’ + @crlf
set @sql = @sql + ‘ set [‘ + @colName + ‘] = replace (convert(nvarchar(max), [‘ + @colName + ‘]), @lookfor collate Latin1_General_CS_AS, @replaceby collate Latin1_General_CS_AS)’ + @crlf
END
ELSE
BEGIN
set @sql = @sql + ‘ update [‘ + @tblName + ‘]’ + @crlf
set @sql = @sql + ‘ set [‘ + @colName + ‘] = replace ([‘ + @colName + ‘], @lookfor collate Latin1_General_CS_AS, @replaceby collate Latin1_General_CS_AS)’ + @crlf
END
END
set @sql = @sql + ‘end’ + @crlf
execute sp_executesql @sql ,
N’@tblName varchar(255), @colName varchar(255), @lookfor varchar(8000), @replaceby varchar(8000)’,
@tblName , @colName, @lookfor, @replaceby
fetch cCursor into @tblName, @colName, @typeName
end
go
select *
from ##wrk
go
No Comments Yet