Use Excel 2010 to read/write to a SQL Server 2008 database using stored procedures

前端 未结 3 1162
无人共我
无人共我 2021-02-04 21:14

We have a SQL Server 2008 database that has stored procedures to handle reads/writes/etc. These procedures are used by a variety of applications internally.

The need ha

3条回答
  •  伪装坚强ぢ
    2021-02-04 21:48

    Hi you can start with this.

    Create Macro Button on your excel file. Click New and then add this code.

    Sub Button1_Click()
    Dim cnt As ADODB.Connection
    Dim rst As ADODB.Recordset
    Dim stSQL As String
    Dim SNfound As String
        'Your sqlserver 2008 connection string
        Const stADO As String = "Provider=SQLOLEDB.1;" & _
        "" & _
        "Initial Catalog=YOurDB;" & _
        "Data Source=YourServer;UID=yourusername;PWD=yourpassword;"
    
    
         'SELECT FROM STORED PROCEDURE
         ' eg: select SN from SNTable where SN=@SN
             stSQL = "exec usp_SelectSN '" & "TESTSN" & "'"  
            Set cnt = New ADODB.Connection
            With cnt
                      .CursorLocation = adUseClient
                      .Open stADO
                      .CommandTimeout = 0
            Set rst = .Execute(stSQL)
            End With
    
                    If rst.RecordCount = 0 Then
                          'NO SN FOUND ON YOUR DB
                    Else
    
                          'RECORDS FOUND SHOW Retrieve SN from DB to message box
                        SNfound = rst.Fields("SN")
    
                        MsgBox ("Found:" & SNfound)
    
                    End If
    
                    Set rst = Nothing
                    Set cnt = Nothing
    
    End Sub
    

    Regards

提交回复
热议问题