SQL循环遍历列并执行REPLACE语句

时间:2016-09-30 12:18:54

标签: sql-server

我正在尝试替换SQL Server中的表中的CRLF字符。一栏的陈述有效,如下:

select REPLACE(REPLACE(col_name,char(13),''), char(10), '') from table_name

现在我想对表格中的每一栏重复这一点。我有以下脚本无效:

Declare @sql varchar(max) = ''

select @sql = @sql + 'select [' + c.name + '] REPLACE(REPLACE(' + c.name + ', char(13),''), char(10), '') from [' + t.name + ']; ' 
from sys.columns c
inner join sys.tables t on c.object_id = t.object_id
where t.name = table_name

EXEC (@sql)

不幸的是,这不起作用,我收到以下错误:

Msg 102, Level 15, State 1, Line 24
Incorrect syntax near 'REPLACE'.
Msg 102, Level 15, State 1, Line 24
Incorrect syntax near 'REPLACE'.
Msg 102, Level 15, State 1, Line 24
Incorrect syntax near 'REPLACE'.
Msg 102, Level 15, State 1

3 个答案:

答案 0 :(得分:2)

两件事;如其他答案所述 在初始[c.name]之后需要有逗号。另外,要在字符串中获取单引号,您需要两个单引号。因此,要将两个单引号放在一起,您需要四个单引号。

select @sql = @sql + 'select [' + c.name + '], REPLACE(REPLACE(' + c.name + ', char(13),''''), char(10), '''') from [' + t.name + ']; ' 
    from sys.columns c
    inner join sys.tables t on c.object_id = t.object_id
    where t.name = 'table_name'

    exec (@sql)

注意:print(@sql)对调试此类问题有很大帮助!

答案 1 :(得分:2)

添加引号,先移除c.name或添加逗号,而不是添加[]使用QUOTENAME:

Declare @sql varchar(max) = ''

select @sql = @sql + 'select ' + QUOTENAME(c.name) + ', REPLACE(REPLACE(' + QUOTENAME(c.[name]) + ', char(13),''''), char(10), '''') from ' + QUOTENAME(t.[name]) + '; ' 
from sys.columns c
inner join sys.tables t 
    on c.object_id = t.object_id
where t.[name] = 'table_name'

EXEC (@sql)

修改

如果您需要更新更改@sql部分:

select @sql = @sql + 'UPDATE ' + QUOTENAME(t.[name]) + ' SET ' + QUOTENAME(c.name) + ' = REPLACE(REPLACE(' + QUOTENAME(c.[name]) + ', char(13),''''), char(10), '''') ; ' 

答案 2 :(得分:1)

您可以尝试这种方式,变量未设置为替换值,引号不是双引号...

Declare @sql varchar(max) = ''

select @sql = @sql + 'select [' + c.name + '] = REPLACE(REPLACE(' + c.name + ', char(13),''''), char(10), '''') from [' + t.name + ']; ' 
from sys.columns c
inner join sys.tables t on c.object_id = t.object_id
where t.name = 'commasep'

select @sql