|
SQL server开发人员提供的查询语句是执行存储过程的SQL,如附件所示:是一个“.sql”的文档
不是类 select * form yyy这样的字符串
请问vba如何写代码连接SQLserver执行这个.SQL文档呢
以下是连接的代码, 我写好了,可以正常接通数据库,就是不知道怎么处理这个.sql命令,请各位老师帮忙,谢谢
Sub test6()
Dim cnn As Object, rst As Object, cat As Object
Dim cnStr As String, strSQL As String
SQL serverl.7z
(787 Bytes, 下载次数: 0)
Dim Brr
On Error Resume Next
Set cnn = CreateObject("ADODB.Connection")
Set rst = CreateObject("ADODB.Recordset")
mydriver = "Provider=sqloledb"
Host = "192.168.10.8"
Database = "YYY"
User = "HERRICK"
pw = "USER123"
cnStr = mydriver & ";Server=" & Host & ";Database=" & Database & ";Uid=" & User & ";Pwd=" & pw & ";option=3"
cnn.Open (cnStr)
If cnn.State = 1 Then
strSQL = ThisWorkbook.Sheets(2).Range("G2")
rst.Open strSQL, cnn, 3
rst.Open strSQL, cnn, adOpenKeyset, adLockOptimistic
Debug.Print rst.RecordCount
Set sht = ThisWorkbook.Sheets(9)
sht.Name = "TG-SQL1"
If rst.RecordCount > 0 Then
Brr = Application.WorksheetFunction.Transpose(cnn.Execute(strSQL).GetRows)
sht.Range("a2").Resize(UBound(Brr), UBound(Brr, 2)) = Brr
k = 0
ReDim Brr(1 To rst.Fields.Count)
For j = 1 To rst.Fields.Count
k = k + 1
ReDim Preserve Brr(1 To k)
Brr(k) = rst.Fields(j - 1).Name
Next
sht.Range("a1").Resize(, UBound(Brr)) = Brr
End If
Else
MsgBox "5:fail"
End If
rst.Close: Set rst = Nothing
cnn.Close: Set cnn = Nothing
ThisWorkbook.Save
End Sub
|
|