我正在将数据库从SQL Server导出到Snowflake,我遇到了一个问题,其中有未知数量的列具有用户注释并在其中有新行字符。问题是数据库有超过280个表,我不想手动查看每个表。我想知道是否有一种方法可以自动完成这项工作。
我目前正在使用SSIS导出数据,并且只在我发现有换行符的列上执行select replace。
我也使用了这个脚本:
declare @NewLine char(2) set @NewLine=char(13)+char(10) update Projects set [PR_ITComment] =Replace([PR_ITComment] , @NewLine,'') WHERE [PR_ITComment] like '%' +@NewLine +'%'发布于 2017-01-21 06:29:24
这与Sean Lange的答案类似,但它解析为每个表一个更新,而不是每个列一个更新。
--declare @schema nvarchar(256) = 'dbo';
--declare @table nvarchar(256) = 'table';
declare @sql nvarchar(max) = '';
set @sql += (select 'update '+t.table_schema+'.'+t.table_name+' set ' +stuff(
( select ', ['+i.column_name +']=replace(replace(['+i.column_name+'],char(10),''''),char(13),'''')'+char(10)
from information_schema.columns i
where i.table_schema=t.table_schema
and i.table_name=t.table_name
and i.data_type in ('char','nchar','varchar','nvarchar','text','ntext')
order by i.ordinal_position
for xml path('')),1,1,'')+';'+char(10)
from information_schema.tables t
where t.table_type='base table'
--and t.table_schema = @schema
--and t.table_name = @table
for xml path (''), type).value('.','varchar(max)')
--print @sql
select @sql
--exec sp_executesql @sql发布于 2017-01-21 06:20:35
这里有一个解决这个问题的方法。这利用了动态sql,因此您不必求助于循环。您可能希望对此进行一些调整,以满足您的需要。您可以添加另一个谓词来阻止列表中的某些表或诸如此类的事情。其工作方式是创建大量的update语句。然后,您只需执行大量的字符串。
declare @SQL nvarchar(max) = ''
select @SQL = @SQL + 'Update ' + quotename(t.name) + ' set ' + quotename(c.name) + ' = replace(Replace(' + quotename(c.name) + ', char(10), ''''), char(13), '''');'
from sys.tables t
join sys.columns c on c.object_id = t.object_id
join sys.systypes st on st.xtype = c.system_type_id
where st.name in ('text', 'ntext', 'varchar', 'nvarchar', 'char', 'nchar')
select @SQL
--Once you are comfortable with the output you can uncomment the line below to actually run this.
--exec sp_executesql @SQL发布于 2017-01-25 04:17:45
如果您能够使用quotes导出数据(这是标准的CSV方式),Snowflake可以简单地使用新行加载数据。您也可以使用转义,但引用更好。
包含3行的示例文件
$ cat data.csv
1,"a",b
2,c,"d1
d2"
3,"e1,e2,
e3",f示例SQL和输出:
create or replace table x(nr int, a string, b string);
put file://data.csv @%x;
copy into x file_format = (field_optionally_enclosed_by = '"');
select * from x;
----+--------+----+
NR | A | B |
----+--------+----+
1 | a | b |
2 | c | d1 |
| | d2 |
3 | e1,e2, | f |
| e3 | |
----+--------+----+https://stackoverflow.com/questions/41773007
复制相似问题