1

我有一个存储过程,可以使用 BCP 将文件写入网络驱动器,方法是在数据库服务器上创建一个临时驱动器,该驱动器映射到另一台服务器上的共享驱动器。它工作正常,但是,我从最后一个EXEC命令返回一个错误,这表示There are open files and/or incomplete directory searches pending on the connection to U:.我猜测它正在尝试在完成写入文件之前执行删除驱动器命令。如果我在运行 proc 后运行语句,它将成功删除驱动器。这是过程:

CREATE PROCEDURE dn_ExportFile
    @ServerName varchar(50),
    @ServerPath varchar(500),
    @FileName varchar(100),
    @Query varchar(max),
    @UserName varchar(100),
    @Password varchar(100),
    @Drive varchar(1) = 'U'
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @cmd VARCHAR(8000)

    --Set up virtual drive pointing to desired path
    SET @cmd = 'NET USE ' + @Drive + ': ' + @ServerPath + ' /user:' + @ServerName + '\' + @UserName + ' ' + @Password
    PRINT @cmd
    EXEC xp_cmdshell @cmd

    --Export data using BCP to virtual drive
    SET @cmd = 'BCP "' + @Query + '" QUERYOUT "' + @Drive + ':\' + @FileName + '" -c -t -T'
    PRINT @cmd
    EXEC xp_cmdshell @cmd

    --Delete virtual drive
    SET @cmd = 'NET USE ' + @Drive + ': /delete'
    PRINT @cmd
    EXEC xp_cmdshell @cmd
END

有没有办法成功删除存储过程中的临时驱动器?

4

1 回答 1

2

我怀疑在调用过程仍在范围内时它不会发生。因此,您可以尝试执行以下操作的包装存储过程:

EXEC dbo.dn_ExportFile ...;

SET @cmd = 'NET USE ' + @Drive + ': /delete';
PRINT @cmd;
EXEC xp_cmdshell @cmd;

Otherwise I still think you're doing this in the wrong place. Have the program that calls this procedure call the command and dictate the path.

于 2012-06-25T19:22:13.060 回答