一个用于远程执行SQL脚本的函数

介绍了一个用于远程连接SQLServer数据库并执行本地SQL脚本的通用函数ExecuteSQLScriptFile,适用于SQLServer2000数据库。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一个用于远程执行SQL脚本的函数

当后台使用SQL Server数据库时,我们不可避免的需要在里面创建视图、存储过程等,但老从企业管理器里面去处理又不太方便,这里提供了一个用于远程连接SQL Server数据库然后执行一个本地SQL脚本的通用函数,不过我对SQL Server没什么深入的研究,高手凑合着看,新手凑合着用^o^。

'=====================================================================================
'函数名称: ExecuteSQLScriptFile
'功能描述: 在指定SQL Server数据库中执行SQL脚本
'输入参数: Server 必需的,服务器名称或IP地址
' Database 必需的,数据库名称
' UserID 必需的,访问数据库的用户名
' Password 必需的,访问数据库的用户密码
' SQLScriptFile 必需的,SQL脚本文件路径名
'返回参数: 脚本执行成功返回True,否则返回False
'使用示例: ExecuteSQLScriptFile "192.168.1.1","NorthwindCS","sa","sa","C:\test.sql"
'相关调用:
'使用注意:
'兼 容 性: 只在SQL Server 2000数据库上测试过
'参考资料:
'作 者: 红尘如烟
'创建日期: 2010-8-7
'=====================================================================================
Public Function ExecuteSQLScriptFile(ByVal Server As String, _
ByVal Database As String, _
ByVal UserID As String, _
ByVal Password As String, _
ByVal SQLScriptFile As String) As Boolean
On Error GoTo Err_ExecuteSQLScriptFile
Dim strSQL As String
Dim strTemp As String
Dim intFileNum As Integer
Dim cnn As Object

intFileNum = FreeFile()
Open SQLScriptFile For Input As #intFileNum
strSQL = ""
Do While Not EOF(1)
Line Input #intFileNum, strTemp
If UCase$(strTemp) <> "GO" Then strSQL = strSQL & strTemp & vbCrLf
Loop
Close #intFileNum
If strSQL <> "" Then
strTemp = "Provider=SQLOLEDB" & _
";Data Source=" & Server & _
";Initial Catalog=" & Database
Set cnn = CreateObject("ADODB.Connection")
cnn.Open strTemp, UserID, Password
cnn.Execute strSQL
cnn.Close
ExecuteSQLScriptFile = True
End If


Exit_ExecuteSQLScriptFile:
Set cnn = Nothing
strSQL = ""
strTemp = ""
Exit Function

Err_ExecuteSQLScriptFile:
If err = 53 Then
MsgBox "指定的SQL脚本文件 '" & SQLScriptFile & "' 不存在。", vbCritical
ElseIf err = -2147217900 Then
MsgBox err.Description, vbCritical, "SQL脚本运行错误"
Else
MsgBox err.Description, vbCritical
End If
Resume Exit_ExecuteSQLScriptFile
End Function
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值