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.
2 Answers
You can use OPENROWSET and where case , pls refer
SELECT a.* FROM OPENROWSET( BULK 'c:\test\values.txt',
FORMATFILE = 'c:\test\values.fmt') AS a;
Comments
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