假设以下#temptable
ID location price quantity comment
----------------------------------------------
1 new york 15 10 nice
实际上,该表有更多列。我想快速选择并对每列执行替换操作:
select
replace(ID, char(10), ' ')
, replace(location, char(10), ' ')
, replace(price, char(10), ' ')
, replace(quantity, char(10), ' ')
, replace(comment, char(10), ' ')
from
#temptable
;
对于多个表,在1000列上执行此操作非常麻烦。所以我试图动态地这样做:
declare @sql nvarchar(max)
declare @column varchar(max)
declare cur cursor for select *
from tempdb.sys.columns
where object_id = object_id('tempdb..#temptable')
fetch next from cur into @column
while @@fetch_status = 0
begin
set @sql = @sql + 'replace(' + @column + ', char(10), ""),'
fetch next from cur;
end
@sql = 'select ' + @sql + ' from #temptable'
select @sql
--sp_execute(@sql)
这是我能想到的最好的,但显然它不起作用。你能帮我把这段代码搞定吗?
答案 0 :(得分:3)
不是使用游标来构建要执行的语句,而是可以这样做:
DECLARE @sql AS NVARCHAR(MAX)
DECLARE @cols AS NVARCHAR(MAX)
SELECT @cols = ISNULL(@cols + CHAR(10) + ',','')
+ 'REPLACE(' + QUOTENAME(name) + ', CHAR(10), '' '')'
FROM tempdb.sys.columns WHERE object_id = object_id('tempdb..#temptable')
SET @sql = N'SELECT ' + @cols + ' FROM #temptable'
EXEC sp_executesql @sql
给定您的样本临时表,这将构建并执行以下语句:
SELECT REPLACE([ID], CHAR(10), ' ')
,REPLACE([location], CHAR(10), ' ')
,REPLACE([price], CHAR(10), ' ')
,REPLACE([quantity], CHAR(10), ' ')
,REPLACE([comment], CHAR(10), ' ') FROM #temptable
你应该从sys.columns中限定查询并为system_type_id
添加一个过滤器,只对具有字符数据类型的列(如167(varchar)或175(char))进行操作,如果它没有意义你也可以在二进制数据上运行替换。
答案 1 :(得分:2)
注意打开游标,关闭游标并释放游标。您还要选择光标的名称列。关于这个主题的好文章 - https://www.mssqltips.com/sqlservertip/1599/sql-server-cursor-example/
declare @sql nvarchar(max) = 'Select '
declare @column varchar(8000)
declare cur cursor for select name
from tempdb.sys.columns
where object_id = object_id('tempdb..#temptable')
Open cur
fetch next from cur into @column;
while @@fetch_status = 0
begin
set @sql = @sql + 'replace(' + @column + ', char(10), '' ''),'
--select @sql
fetch next from cur into @column;
end
close cur
deallocate cur
Set @sql = Substring(@sql,1,Len(@sql)-1) + ' from #temptable'
--select @sql
exec (@sql)