2013-03-23 73 views
1

任何人都會知道如何從SQL Server中讀取文本文件(即連續填充的日誌文件)並將其連續導入到SQL Server表中?如何連續使用SQL Server讀取文本文件?

我想僅在存儲過程中使用T-SQL

除了一次讀取整個文件外,我還沒有在BULK INSERTOPENROWSET中找到任何選項。我將不得不一次重複執行並查找尚未導入的行。 這是一種可能性,但如果文件變大,則效率不高。

是否可以在每次運行時只讀取最新的行?

謝謝! 菲利普

回答

2

你可以爲了使用FileSystemWatcher當日志文件更改

FileSystemWatcher watcher = new FileSystemWatcher(); 

watcher.Path = @"C:\PathOfTheLogfile"; 
watcher.Filter = "MyLogfile.txt"; // You can also use wildcards here. 

watcher.NotifyFilter = NotifyFilters.LastWrite; 
watcher.Changed += new FileSystemEventHandler(Watcher_Changed); 
watcher.Created += new FileSystemEventHandler(Watcher_Changed); 

watcher.EnableRaisingEvents = true; // Start watching. 

... 

private static void Watcher_Changed(object source, FileSystemEventArgs e) 
{ 
    if (e.ChangeType == WatcherChangeTypes.Created) { 
     //TODO: Read log from beginning 
    } else { 
     //TODO: Read log from last position 
    } 
    //TODO: write to MSSQL 
    //TODO: remember last log file position 
} 

有時FileSystemWatcher事件觸發時該文件仍然被寫入得到通知。讀取日誌文件之前,您可能必須添加延遲。

+0

編輯了這個問題,使其更清晰:我正在尋找一個T-SQL唯一的解決方案(如果可能的話)。不管怎麼說,還是要謝謝你。 – 2013-03-23 18:45:24

0

如果您的文件可由Jet提供程序解析,那麼您可以使用linked server作爲文本文件。