如何使用SQL Server连续读取文本文件?

时间:2013-03-23 17:37:28

标签: sql-server import text-files

任何人都知道如何从SQL Server读取文本文件(即连续填充的日志文件)并将其连续导入SQL Server表?

我想在存储过程中使用仅T-SQL

除了一次阅读整个文件外,我在BULK INSERTOPENROWSET中找不到任何选项。我必须反复执行它并查找尚未导入的行。 这是一种可能性,但如果文件变大则效率不高。

是否可以在每次运行时只读取最新的行?

谢谢! 菲利普

2 个答案:

答案 0 :(得分: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事件将触发。您可能必须在读取日志文件之前添加延迟。

答案 1 :(得分:0)

如果您的文件可由Jet提供商解析,则可以对文本文件使用linked server