use excel for sql query

MetLife

Active Member
Joined
Jul 2, 2012
Messages
283
Hi,

I have a sql query, can this be run in excel? Any advice would be appreciated!!!

Drop table [V200_06302023]

Select [MPOLNO]
,[MREC]
,[MACTP]
,[MPRFT]
,[MCOMP]
,[MPOLCT]
,[MSTMIR]
,[MGPMIR]
,[PBR_INDICATOR]
Into [Axis].[dbo].[V200_06302023]
From [Axis].[dbo].[tgt_V200-BCVUL_MISC_V200-20230630-20230630154132]
Where MREC = 1
 

Excel Facts

Bring active cell back into view
Start at A1 and select to A9999 while writing a formula, you can't see A1 anymore. Press Ctrl+Backspace to bring active cell into view.
Here's the script I typically use to run a SQL query in Excel. The actual query and database connection details are entered on the spreadsheet.
VBA Code:
Private Sub RunSQLUpdate()
Dim constr As String
Dim conn As Object
Dim strSQL As String
Dim rs As Object
Sheet10.Range("A12:ZZ1048000").ClearContents
On Error Resume Next

If InStr(1, LCase(Sheet10.Range("A9").Value), "update") > 0 Then
    If MsgBox("Are you sure you want to update the database?", vbYesNo) = vbNo Then Exit Sub
End If

    ' OPEN CONNECTION '
    constr = "provider=sqloledb;Data Source=" & Sheet10.Range("DataSource").Value & ";initial catalog=" & Sheet10.Range("InitCat").Value & ";" & Sheet10.Range("DBSecurity").Value
      
    strSQL = Sheet10.Range("SQLStmt").Value
      
    Set conn = CreateObject("ADODB.Connection")
    conn.Open constr

    

    ' EXECUTE QUERY '
    'conn.Execute strSQL

    'Print result starting in cell C9
    
    Set rs = CreateObject("ADODB.RECORDSET")
    rs.activeconnection = conn
    rs.Open strSQL
      Sheet10.Range("A12").CopyFromRecordset rs

    ' CLOSE CONNECTION '
    conn.Close
    rs.Close
    Set conn = Nothing

    MsgBox "Transaction complete!", vbInformation
End Sub

1702661005904.png
 
Upvote 0

Forum statistics

Threads
1,215,190
Messages
6,123,547
Members
449,107
Latest member
caya

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top