2012-05-21 128 views
-2

我有一個問題:多個查詢在一個查詢中

是否有可能在一個查詢中收集多個查詢?

即在一個窗體我有10個這樣的查詢:

1. SELECT ThisValue FROM thatTable1 WHERE 
2. SELECT ThisValue FROM thatTable2 WHERE 
       ....... 
10.  SELECT ThisValue FROM thatTable10 WHERE 

我應該在哪裏寫即該代碼Access.It可以在Access或只有我能做到這一點在MS SQL和... 。

CREATE PROC dbo.proc_app_CollectControlData 
AS 
    SET NOCOUNT ON 

    DECLARE @t TABLE 
    (
     CONTROLNAME nvarchar(74), 
     CONTROLVALUE nvarchar(255) 
    ) 

    -- Now we collect the data for the 10 different controls 
    INSERT INTO @t 
    (CONTROLNAME, CONTROLVALUE) 
    SELECT 'MyFirstControl', 
      ThisValue 
    FROM dbo.ThatTable 
    WHERE Condition1 

    ... 

    INSERT INTO @t 
    (CONTROLNAME, CONTROLVALUE) 
    SELECT 'MyTenthControl', 
      ThisValue 
    FROM dbo.ThatTable 
    WHERE Condition10 

    -- And now we return all found data to the client 
    SELECT * FROM @ 
    SET NOCOUNT OFF 
GO 

回答

3

我認爲你正在尋找UNION Operator

SELECT 'MyFirstControl' AS ControlName, ThisValue AS ControlValue 
FROM thatTable1 
WHERE Condition1 
UNION ALL 
SELECT 'MySecondControl' AS ControlName, ThisValue AS ControlValue 
FROM thatTable2 
WHERE Condition2 
UNION ALL 
SELECT 'MyThirdControl' AS ControlName, ThisValue AS ControlValue 
FROM thatTable3 
WHERE Condition3 
+0

不是聯盟所有,我試圖找到另一種方式 – Baper

+1

爲什麼不聯盟所有?這對於你所提出的要求來說是完美的。詢問如何做某件事並不是很有幫助,然後當你被告知可以完成的方式時,指定你需要以不同的方式完成。如果你不想用'UNION' /'UNION ALL'來完成,那麼你應該在你的問題中解決這個問題。 – GarethD

+0

http://social.msdn.microsoft.com/Forums/en-US/accessdev/thread/e3acc5af-1bd9-42de-93f1-209f4dfc11ed/#2b9484a2-9b58-4048-a57e-85e515477c8e – Baper

3
SELECT ThisValue FROM thatTable1 WHERE ... 
UNION ALL 
SELECT ThisValue FROM thatTable2 WHERE ... 
UNION ALL 
SELECT ThisValue FROM thatTable10 WHERE ... 
+0

不UNIONALL。我想另闢蹊徑 – Baper

+2

你介意爲什麼你不想使用已經專門被設計做你所要求的操作員制定? – Karl

+0

somthing like [this](http://social.msdn.microsoft.com/Forums/en-US/accessdev/thread/e3acc5af-1bd9-42de-93f1-209f4dfc11ed/#2b9484a2-9b58-4048-a57e-85e515477c8e) – Baper