VBA连接到SQL Server

时间:2017-06-14 05:57:15

标签: sql-server vba

将VBA连接到SQL Server时遇到问题:

Sub ConnectSQLServer()

Dim cmd As ADODB.Command
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim strConn As String

Dim par As ADODB.Parameter
Dim strSQL As String

strConn = "DRIVER=SQL Server;SERVER=CHU-AS-0004;DATABASE=RTC_LaplaceD_DEV;Trusted_Connection=Yes;"

Set conn = New ADODB.Connection
conn.Open strConn

Set cmd = New ADODB.Command
cmd.CommandText = "dbo.Version"
cmd.CommandType = adCmdStoredProc
cmd.ActiveConnection = conn

rs.Open = "SELECT * FROM [dbo].[Version]"

cmd.Execute rs
Set conn = Nothing
Set cmd = Nothing


sConnString = ""
End Sub

我只想从名为[dbo].[Version]的表中选择所有值,但是当我执行它时,我收到错误:

  

编译错误:预期的功能或变量'

并突出显示rs.Open行。

你能帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

Open是一种方法,无法使用=进行设置。

你可能想要这样的东西:

rs.Open "SELECT * FROM [dbo].[Version]", conn

调用Open后,您可以使用EOF属性和MoveNext方法遍历Recordset的行:

Do While Not rs.EOF
    Debug.Print rs.Fields(1)
    'You could also use rs!FieldName, where FieldName is the name of a column
Loop

答案 1 :(得分:0)

将您的代码更改为以下内容:

Set cmd = New ADODB.Command
cmd.CommandText = "SELECT * FROM [dbo].[Version]"
cmd.CommandType = adCmdText
cmd.ActiveConnection = conn

Set rs = cmd.Execute

Do While Not rs.EOF
    'do something with rs.Fields(0) '
    rs.MoveNext
Loop
Set conn = Nothing
Set cmd = Nothing

rs.Fields是一个基于零的集合,表示第一个字段是0,而不是1。 您可以通过rs.Fields(1),rs.Fields(2)等获取后续字段。或者您可以使用字段名称,语法为rs.Fields(“MyFieldName”)。

注意使用字符串命令(“SELECT * FROM ..”)时,CommandType是adCmdText。 Recordset的语法是SET rs = cmd.Execute。你也必须在循环中调用MoveNext,否则你会陷入循环!