Wednesday, March 21, 2012

Replace chars in any field of a table

I need to strip some puntcuation from any field in a given table.
I'd rather like to avoid using the replace () for each field in the
table.
Anyone have a nifty way do this?
Is there a special name that I can use in the replace that means the
entire row?
(other than syntax, something like REPLACE(@.ROW,CHAR(39),'') )
tia
RobYou could try the following. It uses a cursor, which I'm sure is a bad
thing. But it should work. I didn't try it out. The cursor grabs
column names for columns that are of a varchar type. That may not be
what you need. But the Replace function requires a string, so there ya
go. Maybe (most likely) someone will have a better way to do this.
Hope it helps.

Jennifer

Declare @.Tbl nvarchar(100)
Declare @.Qry nvarchar(1000)
Declare @.N nvarchar(100)

Set @.Tbl = 'TableName'

DECLARE col_cursor CURSOR FOR
select name
from syscolumns
where id = object_id(@.Tbl)
and xtype = 167
order by colid

OPEN col_cursor
FETCH NEXT FROM col_cursor into @.N

WHILE @.@.FETCH_STATUS = 0
BEGIN
Set @.Qry = 'Update ' + @.Tbl + ' Set ' + @.N + ' = REPLACE (' + @.N +
', ''-'' , '''')'
EXEC sp_executesql @.Qry
FETCH NEXT FROM col_cursor into @.N
END

CLOSE col_cursor
DEALLOCATE col_cursor

No comments:

Post a Comment