如何替换SQL Server中每个表中的字符?

时间:2018-03-13 04:53:10

标签: sql-server

我想替换数据库每个表的每一列中的单个字符;但是,我不希望逐桌进行。 有没有办法一次性完成整个事情?

1 个答案:

答案 0 :(得分:1)

假设只修改文本值,您可以执行以下操作。

IF(NOT EXISTS (SELECT * FROM sys.tables where name = 'TEMPQUERYTABLE' and type_desc = 'USER_TABLE'))
BEGIN
    SELECT T.name AS Table_Name ,
           C.name AS Column_Name ,
           P.name AS Data_Type ,
           P.max_length AS Size ,
           CAST(P.precision AS VARCHAR) + '/' + CAST(P.scale AS VARCHAR) AS Precision_Scale
           INTO TEMPQUERYTABLE
    FROM   sys.objects AS T
           JOIN sys.columns AS C ON T.object_id = C.object_id
           JOIN sys.types AS P ON C.system_type_id = P.system_type_id
    WHERE  T.type_desc = 'USER_TABLE' AND P.name in ('nvarchar','varchar') AND T.name <> 'TEMPQUERYTABLE'
END

DECLARE @SQL NVARCHAR(MAX)
DECLARE @Old_value VARCHAR(10)
DECLARE @New_value VARCHAR(10)
SET @Old_value = 'xx'
SET @New_value = 'yy'
SET @SQL = ''

SELECT @SQL = @SQL + 'UPDATE ' + Table_Name + ' SET ' + Column_Name + ' = REPLACE(' + Column_Name + ',' + @Old_value +','+ @New_value + ')' + CHAR(13) + CHAR(10)
FROM TEMPQUERYTABLE

EXEC(@SQL)

--DROP TABLE TEMPQUERYTABLE

但我很想知道为什么你首先需要做这件事。