从SQL表中删除字符

时间:2014-04-07 15:13:27

标签: c# sql stored-procedures

我有大约80个表(每个表有大约12,000行和190列)

我需要删除数据中的几个字符来清理数据。 (ƒ,€和¢)

这些字符出现在整个数据库中(可以在数据中的任何位置),我需要删除所有这些字符。有没有有效的方法呢?

我尝试编写C#应用程序 - 使用datareader读取数据,然后检查字符的出现然后将其删除,最后将数据更新回表。但是,这种方法太耗时了。

2 个答案:

答案 0 :(得分:1)

你可以调用一些T-SQL来执行搜索并替换

请参阅Search and replace part of string in database

中的答案
UPDATE
    Table
SET
    Column = Replace(Column, 'find value', 'replacement value')
WHERE
    xxx

答案 1 :(得分:1)

我确信有更有效的方法,但是这样的方法对你有用。

我正在使用系统表/视图来获取数据库和列的列表,然后使用动态SQL来构建更新语句。作为一次性过程,这应该没问题。

------------------------------------------------------------------------------
-- Define find/replace values here
------------------------------------------------------------------------------
IF OBJECT_ID('tempdb..#FindAndReplace') IS NOT NULL DROP TABLE #FindAndReplace
CREATE TABLE dbo.#FindAndReplace(
    FindValue VARCHAR(255) PRIMARY KEY,
    ReplaceValue VARCHAR(255)
)

INSERT INTO #FindAndReplace SELECT 'ƒ', 'replacement'
INSERT INTO #FindAndReplace SELECT '€', 'goes'
INSERT INTO #FindAndReplace SELECT '¢', 'here'


------------------------------------------------------------------------------
-- Then build and execute replace statements here
------------------------------------------------------------------------------
--loop through all tables
DECLARE @TableName VARCHAR(255)
DECLARE TableCursor CURSOR FOR
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES

OPEN TableCursor
FETCH NEXT FROM TableCursor 
INTO @TableName
WHILE @@FETCH_STATUS = 0
BEGIN

    --then all columns
    DECLARE @ColumnName VARCHAR(255)
    DECLARE ColumnCursor CURSOR FOR
    SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME = @TableName
    AND DATA_TYPE IN ('nvarchar', 'varchar')

    OPEN ColumnCursor
    FETCH NEXT FROM ColumnCursor 
    INTO @ColumnName
    WHILE @@FETCH_STATUS = 0
    BEGIN

        --then all find-replace values
        DECLARE @FindValue VARCHAR(255)
        DECLARE @ReplaceValue VARCHAR(255)
        DECLARE FindReplaceCusor CURSOR FOR
        SELECT FindValue, ReplaceValue
        FROM #FindAndReplace

        OPEN FindReplaceCusor
        FETCH NEXT FROM FindReplaceCusor 
        INTO @FindValue, @ReplaceValue
        WHILE @@FETCH_STATUS = 0
        BEGIN

            DECLARE @SQL NVARCHAR(MAX)
            SET @SQL = 'UPDATE [' + @TableName + '] SET [' + @ColumnName + '] = REPLACE([' + @ColumnName + '], ''' + @FindValue + ''', ''' + @ReplaceValue + ''') WHERE [' + @ColumnName + '] LIKE ''%' + @FindValue + '%'''
            PRINT @SQL
            EXEC sp_executesql @SQL

        FETCH NEXT FROM FindReplaceCusor INTO @FindValue, @ReplaceValue
        END
        CLOSE FindReplaceCusor
        DEALLOCATE FindReplaceCusor

    FETCH NEXT FROM ColumnCursor INTO @ColumnName
    END
    CLOSE ColumnCursor
    DEALLOCATE ColumnCursor

FETCH NEXT FROM TableCursor INTO @TableName
END
CLOSE TableCursor
DEALLOCATE TableCursor