CREATE PROCEDURE SPCheckDirectoryExists
(
@chkdirectory as nvarchar(4000)
)
AS
SET NOCOUNT ON
BEGIN
DECLARE @folder_exists as int
DECLARE @file_results table(file_exists int,file_is_a_directory int,parent_directory_exists int)
INSERT INTO @file_results
(file_exists, file_is_a_directory, parent_directory_exists)
EXEC MASTER.dbo.xp_fileexist @chkdirectory
SELECT @folder_exists = file_is_a_directory
FROM @file_results
--script to create directory
IF @folder_exists = 0
BEGIN
EXECUTE master.dbo.xp_create_subdir @chkdirectory
PRINT @chkdirectory + ' created on ' + @@servername
END
ELSE
PRINT 'Directory already exists'
END
使用上述存储过程
EXEC SPCheckDirectoryExists '\\SampleNetworkpath\Test\Test1'
它将在测试文件夹中检查并创建Test1文件夹,
如果\\SampleNetworkpath\Path
投掷错误,
如何解决此问题, 在此先感谢,
答案 0 :(得分:2)
您还需要检查该目录。这样的事情,使用相同的逻辑......
CREATE PROCEDURE SPCheckDirectoryExists
(
@chkdirectory as nvarchar(4000)
)
AS
SET NOCOUNT ON
BEGIN
DECLARE @folder_exists as int
DECLARE @file_results table(file_exists int,file_is_a_directory int,parent_directory_exists int)
DECLARE @folder_results table(file_exists int,file_is_a_directory int,parent_directory_exists int)
DECLARE @chkdirectory2 nvarchar(4000) = reverse(right(reverse(@chkdirectory),len(@chkdirectory) - charindex('\',reverse(@chkdirectory))))
DECLARE @folder_exists2 int
INSERT INTO @file_results
(file_exists, file_is_a_directory, parent_directory_exists)
EXEC MASTER.dbo.xp_fileexist @chkdirectory
INSERT INTO @folder_results
(file_exists, file_is_a_directory, parent_directory_exists)
EXEC MASTER.dbo.xp_fileexist @chkdirectory2
SELECT @folder_exists = file_is_a_directory
FROM @file_results
SELECT @folder_exists2 = file_is_a_directory
FROM @folder_results
--script to create directory
IF @folder_exists = 0 and @folder_exists2 = 1
BEGIN
EXECUTE master.dbo.xp_create_subdir @chkdirectory
PRINT @chkdirectory + ' created on ' + @@servername
END
ELSE
PRINT 'Directory already exists or parent directory was invalid'
END
答案 1 :(得分:0)
使用您的逻辑的动态脚本。
CREATE PROCEDURE SPCheckDirectoryExists
(
@chkdirectory as nvarchar(4000)
)
AS
SET NOCOUNT ON
BEGIN
DECLARE @pos INT,@NewPath AS NVARCHAR(256)
WHILE(charindex('\',@chkdirectory) > 0)
begin
select @pos = CHARINDEX('\',@chkdirectory,0)
IF (@NewPath <> '')
SET @NewPath = @NewPath + '\'
SET @NewPath =ISNULL(@NewPath,'') + SUBSTRING(@chkdirectory,0,CHARINDEX('\',@chkdirectory,@pos-1))
DECLARE @folder_exists as int
DECLARE @file_results table(file_exists int,file_is_a_directory int,parent_directory_exists int)
INSERT INTO @file_results
(file_exists, file_is_a_directory, parent_directory_exists)
EXEC MASTER.dbo.xp_fileexist @NewPath
SELECT @folder_exists = file_is_a_directory
FROM @file_results
--script to create directory
IF @folder_exists = 0
BEGIN
EXECUTE master.dbo.xp_create_subdir @NewPath
PRINT @NewPath + ' created on ' + @@servername
END
ELSE
PRINT 'Directory already exists'
SET @chkdirectory = SUBSTRING(@chkdirectory,@pos+1,len(@chkdirectory))
END
END