在sql server中检查文件是否存在? [英] Check for file exists or not in sql server?

查看:56
本文介绍了在sql server中检查文件是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解决方案:http://www.tech-recipes.com/rx/30527/sql-server-how-to-check-if-a-file-exists-in-a-directory/

使用 stackoverflow 问题就这个问题发表了一篇文章来帮助他人.

Made a post about this question using stackoverflow question to help others.

id  filepath

1   C:\vishwanath\21776656.docx
2   C:\vishwanath\vish\s_srv_req_2009.txt
3   C:\Users\dalvi\DW\DW20SharedAmd64.exe
4   C:\Users\dalvi\1.txt

我在我的数据库服务器中创建了这样的表,我已经在文件路径列中存储了文件路径,现在我必须使用 sql 检查文件是否存在于我的机器中,如果存在我需要添加临时我的表中的列显示是,如果存在,则不存在.

I've table like this created in my db server, I've stored file paths in it filepath column, now I've to check using sql whether the file exists in my machine, if it exists I need to add temporary column in my table showing yes if exists and no it doesn't exists.

我编写了这段代码,它适用于 1 个文件,但我不知道如何将它用于我的表.

I wrote this code which works for 1 file But I don't know how to use it for my table.

DECLARE @isExists INT
exec master.dbo.xp_fileexist 'C:\vishwanath\21776656.docx', 
@isExists OUTPUT
SELECT case @isExists 
when 1 then 'Yes' 
else 'No' 
end as isExists

最终输出应该是这样的

id  filepath                                 Isexists

1   C:\vishwanath\21776656.docx               Yes
2   C:\vishwanath\vish\s_srv_req_2009.txt     Yes
3   C:\Users\dalvi\DW\DW20SharedAmd64.exe     Yes
4   C:\Users\dalvi\1.txt                      No

推荐答案

像这样创建一个函数:

CREATE FUNCTION dbo.fn_FileExists(@path varchar(512))
RETURNS BIT
AS
BEGIN
     DECLARE @result INT
     EXEC master.dbo.xp_fileexist @path, @result OUTPUT
     RETURN cast(@result as bit)
END;
GO

编辑您的表并添加一个计算列 (IsExists BIT).将表达式设置为:

Edit your table and add a computed column (IsExists BIT). Set the expression to:

dbo.fn_FileExists(filepath)

然后只需选择:

SELECT * FROM dbo.MyTable where IsExists = 1

更新:

在计算列之外使用函数:

To use the function outside a computed column:

select id, filename, dbo.fn_FileExists(filename) as IsExists
from dbo.MyTable

更新:

如果函数为已知文件返回 0,则可能存在权限问题.确保 SQL Server 的帐户具有足够的权限来访问文件夹和文件.只读应该足够了.

If the function returns 0 for a known file, then there is likely a permissions issue. Make sure the SQL Server's account has sufficient permissions to access the folder and files. Read-only should be enough.

是的,默认情况下,网络服务"帐户在大多数文件夹中都没有足够的权限.右键单击相关文件夹并选择属性",然后单击安全"选项卡.单击编辑"并添加网络服务".点击应用"并重新测试.

And YES, by default, the 'NETWORK SERVICE' account will not have sufficient right into most folders. Right click on the folder in question and select 'Properties', then click on the 'Security' tab. Click 'Edit' and add 'Network Service'. Click 'Apply' and retest.

这篇关于在sql server中检查文件是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆