1. We have moved to a new forum! There may be a few things not working properly so please let us know if you find a bug. Remember to use the bbCode [ sql ] tag for SQL statements.

How can I perform a table wide replace statememt?

Discussion in 'SQL - Questions and Answers' started by BigJohn, May 25, 2006.

  1. BigJohn New Member

    Dialect: SQL 92
    How can I extend the SQL Server replace statement, to be performed table wide?
  2. BigJohn New Member

    Dialect: T-SQL
    SQL:

    CREATE procedure tableReplace

    @tableName varchar(100),
    @searchExpression varchar(100),
    @replaceExpression varchar(100)
    as

    ----------------------------------------------------------------------------------------
    --
    -- Author: J.R.Sansom (john.sansom@bcs.org)
    -- Description: An extension of the SQL "Replace" statement to apply the feature
    -- table wide. This procedure is very useful for cleaning data,
    -- such as removing quotes, carriage returns, commas etc.
    --
    -- Requirements: - Requires tableName be specififed.
    -- - Requires that the search expression be defined.
    -- - Requires that the replace expression be defined.
    --
    -- Example Execution
    --
    -- exec tableReplace
    -- @tableName = 'TABLE_NAME,
    -- @searchExpression = 'char(13)',
    -- @replaceExpression = '~'
    --
    --
    -- Hint: Find ASCII Lookup tables at http://www.lookuptables.com/
    --
    ----------------------------------------------------------------------------------------



    set nocount on

    --Delcare the variables for use with this procedure
    declare @SQLText varchar(8000)
    declare @ColumnName varchar(100)

    --Create a cursor to cycle through all of the columns.
    declare cXursor cursor for
    select column_name
    from information_schema.columns
    where table_name=@tableName
    order by ordinal_position
    open cXursor
    fetch next
    from cXursor
    into @ColumnName


    --Loop through the exectuion phase while a "next" cursor result is available.
    while @@fetch_status=0
    begin
    --Creat the SQL query to apply the update statement to the current column
    set @SQLText=' update ' + @tableName +
    ' set ' + @ColumnName + ' = replace( ' + @ColumnName + ' , ' +
    @searchExpression + ' ,''' +
    @replaceExpression + ''') '
    --Execute the generated query.
    exec (@SQLText)

    --Inform the user of progress.
    print 'Column ' + @columnName + ' updated sucessfully.'

    fetch next
    from cXursor
    into @ColumnName
    end

    --Free up the resource taken by the cursor.
    close cXursor
    deallocate cXursor

    go

Share This Page