【发布时间】:2023-04-07 02:54:01
【问题描述】:
我需要导入这种格式的文件:
PParent line has some fields with fixed width
CChild line of Parent Has fixed width with different widths than Parent
CAnother Child Fixed width consistent with Child-lines but not Parent
PSecond Parent has more fields again fixed width like other Parents
CThird Child This time belong to 2nd Parent as that's the preceding P-line
因此,固定列的宽度取决于第一个字符是 P 还是 C。我没有提出这种文件格式,但我是需要处理它的傻瓜……我'目前正在阅读它(简化):
create table #fixed (
line varchar(max)
)
create table #link (
id int identity,
parent int,
linetype char,
line varchar(max)
)
bulk insert #fixed from '\\unc\path\to\file.txt'
with (
fieldterminator = ''
)
insert into #link(linetype, line)
select substring(line, 1, 1), line
from #fixed
update c set
c.parent = p.id
from #link c
cross apply (
select top 1 id from #link
where linetype = 'P' and id < c.id
order by id desc
) p
where c.linetype = 'C'
这可行,但我一般不喜欢它,我特别担心 SQL Server 以任意顺序插入#link,从而丢失update 中正确的父子关系,尤其是对于较大的文件不仅仅是这 5 行。
但我看不到在此处强制使用order 的方法,或者使用使用格式文件的bulk insert 导入此固定宽度和可变宽度格式。
编辑: 我看到的一种方法是使用openrowset(bulk '\\unc\file.txt', single_clob) 读取文件并手动提取行。我现在的主要问题是,我是否应该对insert into #link 的这个顺序感到足够担心,这需要切换为single_clob 阅读?
【问题讨论】:
-
你能利用像SSIS这样的技术吗?您将能够读入您的平面文件,并在读入时为每一行分配一个连续的行号。
-
我仅限于这样做是一段 T-SQL,当另一个进程在文件夹中检测到文件时可以存储和运行它。
标签: sql-server tsql sql-server-2005 fixed-width