[英]Using Parameters in SQL query with sub-query
我有一個相當復雜的SQL查詢與嵌套子查詢。 當我嘗試在Microsoft Query中使用參數時,我說我可以在不能以圖形方式表示的查詢中使用參數。 所以我需要另一種選擇。 我認為您可以將SQL查詢作為字符串放在單元格中,然后讓宏運行它。 我有什么想法可以做到這一點?
謝謝
-Jesse
以下是我在Excel 2007中解決Microsoft Query限制的方法:
SELECT NULL AS Test
)並將其插入到工作表中。 ?
”寫出或粘貼所需的查詢?
'參數約定,然后單擊確定。 這個想法繞過了MS Query提供的GUI,它具有底層引擎所沒有的任意限制。
這適用於許多復雜的查詢,但不是全部。 當我遇到MS Query完全拒絕消化的查詢時,我要么重構查詢(如果可行),要么在SQL服務器上創建一個VIEW
並對其進行查詢。
不幸的是? 不適用於我的大多數查詢,其中很多不一定適合轉換為視圖。
我使用的主要替代方法是獲取宏來返回代碼
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
我希望微軟能夠修復它為更復雜的查詢返回錯誤的錯誤,因為我發現只是為了返回一個簡單的數據集而創建宏令人沮喪
解決此問題的另一種方法是使用存儲過程
CREATE PROCEDURE [dbo].[yourprocedure] @DATEFROM DATETIME, @DATETO DATETIME
AS
SELECT Query
where date >= @datefrom
and date <= @dateto
然后在表屬性上單擊“連接屬性”按鈕,然后單擊“定義”選項卡。 在命令文本部分:
EXEC yourprocedure @DATEFROM = ?, @DATETO = ?
並直接? 到你想要的細胞
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.