我从文本文件创建一个表,如下所示:
SELECT *
INTO new_table
FROM OPENROWSET('MSDASQL',
'Driver={Microsoft Access Text Driver (*.txt, *.csv)};
Extended Properties="text;HDR=YES;FMT=Delimited"'
,'select * from C:\text_file.txt')
它正在运行,但所有列都是使用数据类型varchar(255)
创建的。我想切换到nvarchar(max)
。
问题:是否可以将默认类型设置为nvarchar(max)
?在SQL Server设置或其他地方?
重要提示:所有要点都不是定义列名,因为它们可能会有所不同。所以我做不到SELECT CAST(Column1 AS NVARCHAR(MAX))...
答案 0 :(得分:0)
1-为列表创建临时表
SELECT top 1 * INTO #dt
FROM OPENROWSET('MSDASQL',
'Driver={Microsoft Access Text Driver (*.txt, *.csv)};
Extended Properties="text;HDR=YES;FMT=Delimited"'
,'select * from C:\text_file.txt')
2-为新表创建sql脚本并添加所有具有nvarchar(max)
的列declare @Rows int = 1
declare @colName nvarchar(150)
declare @Id int = 0
declare @MySql nvarchar(max)
set @MySql = 'CREATE TABLE new_table ( '
WHILE @Rows>0
BEGIN
SELECT top 1 @Id = ORDINAL_POSITION, @colName =COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = N'#dt' and ORDINAL_POSITION >@Id
set @Rows =@@RowCount
if @Rows>0
begin
set @MySql = @MySql + @colName + ' nvarchar(max) ,'
end
END
set @MySql = substring(@MySql,0,(len(@MySql)-1)) +')'
exec (@MySql)
3-运行插入脚本并将数据填充到真实表格
SELECT * INTO new_table
FROM OPENROWSET('MSDASQL',
'Driver={Microsoft Access Text Driver (*.txt, *.csv)};
Extended Properties="text;HDR=YES;FMT=Delimited"'
,'select * from C:\text_file.txt')