简体   繁体   中英

Open a Locked Text File with SQL Server

When I try to

BULK INSERT table FROM 'c:\file.txt'

I get

Msg 4861, Level 16, State 1, Line 1
Cannot bulk load because the file "c:\file.txt" could not be opened. Operating system error code 32(The process cannot access the file because it is being used by another process.).

error since the file is a log file opened by another process.

However with C# I can open the file with System.IO.FileShare.ReadWrite as:

using (System.IO.FileStream fileStream = new System.IO.FileStream("c:\\file.txt", System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite))
        {
            using (System.IO.StreamReader streamReader = new System.IO.StreamReader(fileStream))
            {
                file = streamReader.ReadToEnd();
            }
        }

Is there a way to have that ReadWrite share functionality within SQL Server (bulk insert or any other)?

Thanks

由于您无法控制SQL Server在后台使用的OpenFile标志,因此您可能必须在批量插入之前将文件复制到临时文件。

(Reposted from my answer on DBA.SE since you deleted the question.)

BULK INSERT attempts to take a write lock on the source file to ensure that no other process is concurrently modifying the file while the read occurs. This is done to stabilize the file format, since a read could end up attempting to process a partial line being written by a concurrent writer.

Because the log file is opened for writing by another process already, this is incompatible access, and you get that error.

About the code:

  • FileAccess determines what you are going to do with the file.
  • FileShare determines what others are allowed to do with the file while you have it open.

The logging process would use FileAccess.Write or FileAccess.ReadWrite , and given that your code succeeds, probably FileShare.Read -- this would prevent others from writing to the file simultaneously, but allows them to read the contents. Your code only requests read access, and so this is compatible. If you re-run the code and request write access ( FileAccess.Write ) instead, the code will fail.

To use BULK INSERT to import this file, you'll have to make a copy and import that, then there won't be any file locks involved.

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