您的位置:首页 > 数据库

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

2011-08-02 12:38 330 查看

一个用于远程执行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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐