简体   繁体   English

在SQL Server 2005中使用SQL读取文本文件

[英]Reading a text file using SQL in SQL server 2005

I need to read 2nd line and last line of a text file in SQL server 2005. The content of the line will be tab separated. 我需要在SQL Server 2005中阅读文本文件的第二行和最后一行。该行的内容将以制表符分隔。 Can somebody tell me what is a general way used to achieve this? 有人可以告诉我实现这一目标的一般方法是什么? Note that I can not create temporary tables in the database as I have only read only access to it. 请注意,由于我只有只读访问权限,因此无法在数据库中创建临时表。

You can use OPENROWSET and where case , pls refer 您可以使用OPENROWSET,如果是case,请参考

http://msdn.microsoft.com/en-us/library/ms190312.aspx http://msdn.microsoft.com/en-us/library/ms190312.aspx

SELECT a.* FROM OPENROWSET( BULK 'c:\test\values.txt', 
   FORMATFILE = 'c:\test\values.fmt') AS a;

If you know row numbers (in my test txt file 5 lines) 如果您知道行号(在我的测试txt文件中5行)

DECLARE @str nvarchar(max) = (SELECT line FROM OPENROWSET (BULK 'c:\your_file.txt' , SINGLE_CLOB ) AS xmlData(line))
;WITH cte AS (
         CAST('<r>'+REPLACE(@str, CHAR(13),'</r><r>')+'</r>' AS XML).query('/r[2]').value('.','varchar(max)') col2,
         CAST('<r>'+REPLACE(@str, CHAR(13),'</r><r>')+'</r>' AS XML).query('/r[5]').value('.','varchar(max)') col5                
 )
 SELECT CASE WHEN col2 = '' THEN NULL ELSE col2 END col2,  
        CASE WHEN col5 = '' THEN NULL ELSE col5 END col5
 FROM cte

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM