Reputation: 395
I have a fairly complicated SQL query with a nested subquery. When I try to use parameters in Microsoft Query is say I can use parameters in queries that cant be represented graphically. So I need another option. I think you can place your SQL query in a cell as a string then have a Macro run it. Any ideas how I could do this?
Thanks
-Jesse
Upvotes: 4
Views: 7050
Reputation: 11
Another way to solve this is to use stored procedures
CREATE PROCEDURE [dbo].[yourprocedure] @DATEFROM DATETIME, @DATETO DATETIME
AS
SELECT Query
where date >= @datefrom
and date <= @dateto
then on the table properties click Connection Properties button, then click the Definition tab. In the Command Text section:
EXEC yourprocedure @DATEFROM = ?, @DATETO = ?
and direct the ? to the cells you want
Upvotes: 1
Reputation: 11
Unfortunately the ? doesn't work for most of my queries and a lot of them are not necessarily suited to being turned into views.
The main alternative I use is getting a macro to return the code
Dim Con As New ADODB.Connection
Dim RS As New ADODB.Recordset
Dim server, Database As String
Dim Data as Worksheet
Set data = ThisWorkBook.Worksheets("data")
'rename field here and elsewhere to your variable eg SD or StartDate
Dim field as string
server = "servername"
Database = "database"
'set connection string
If Con.State <> 1 Then
Con.ConnectionString = "Provider=SQLOLEDB;Data Source=" & server & ";Initial Catalog=" & Database & ";Integrated Security=SSPI;"
'this is just setting the connection time out to infinite
setcono:
Con.ConnectionTimeout = 0
Con.CommandTimeout = 0
'this is making sure it set the connection time out to infinite
If Con.ConnectionTimeout > 0 Then GoTo setcono
If Con.CommandTimeout > 0 Then GoTo setcono
Con.Open
Set oRS = New ADODB.Recordset
oRS.ActiveConnection = Con
field = Range("A2").value
oRS.Source = "YOUR SQL QUERY "
oRS.Source = oRS.Source & " WHERE field = '" & field & "'"
oRS.Open
data.Range("A2").CopyFromRecordset oRS
End If
oRS.Close
Con.Close
If Not oRS Is Nothing Then Set oRS = Nothing
If Not Con Is Nothing Then Set oCon = Nothing
I would love Microsoft to fix the bug where it returns errors for the more complex queries as I find it frustrating creating macros just for the sake of returning a simple dataset
Upvotes: 0
Reputation: 1365
Here's what I do to work around the limitations of Microsoft Query in Excel 2007:
SELECT NULL AS Test
, for example) in Microsoft Query and insert it into the worksheet.?
' convention for parameters, then click OK.The idea is the bypass the GUI that MS Query provides, which has some arbitrary limitations that the underlying engine does not.
This works for many complex queries, but not all. When I encounter a query that MS Query refuses to digest at all, I either refactor the query (when feasible) or create a VIEW
on the SQL server and query against that.
Upvotes: 1