我正在寻找一个解决方案来计算带有脚本任务的平面文件中的列(非行),并将它们存储到变量中。
提前致谢
btw,SQL Server 2008R2
答案 0 :(得分:0)
我认为您可以使用OpenRowSet
或OpenDataSource
select *
into #temp
from OpenRowSet(...)
where 1=2
select count(*)
from tempdb.sys.columns
where object_id = object_id('tempdb..#temp')
drop table #temp
OpenRowSet会喜欢
select * into #temp from openrowset('MSDASQL', 'driver={Microsoft Text Driver (*.txt; *.csv)}; defaultdir=C:\MyFolder;','select * from file.csv')
然后使用sp_OA过程启动Scripting.FileSystemObject。打开文件,然后阅读第一行。 #columns =#逗号+ 1。
opendatasource()
对文本文件的功能:
select *
from OpenDataSource( 'Microsoft.Jet.OLEDB.4.0',
'Data Source="c:\files";Extended properties="Text;hdr=no"')...clients#txt
sp_OA方法:
declare @FileName varchar(100)
set @FileName = '<Put your filename here>'
declare @oFSO int,
@oTSO int,
@line varchar(500)
-- get the first line from the file
execute sp_OACreate 'Scripting.FileSystemObject', @oFSO OUTPUT
execute sp_OAMethod @oFSO, 'OpenTextFile', @oTSO OUTPUT, @FileName
execute sp_OAMethod @oTSO, 'ReadLine', @line OUTPUT
execute sp_OAMethod @oTSO, 'Close'
execute sp_OADestroy @oTSO
execute sp_OADestroy @oFSO
;with CTE AS
(
select Col = substring(@line, Number, 1)
from dbo.Numbers
where Number <= len(@line)
)
select ColumnCount = count(*) + 1, @line
from CTE
where Col = ','
有关OPENDATASOURCE的更多信息 - ad-hoc-querying-text-files