简体   繁体   中英

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. 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

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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