2017-08-01 55 views
-1

我使用SQL Server:如何的2個存儲過程的結果相結合,該數據在那裏我有2種存儲過程結合起來,網格視圖

1存儲過程:

CREATE PROCEDURE A 
AS 
    SELECT DISTINCT 
     TC.*,  MS.* 
    FROM 
     VIEW1 TC, 
     View2 MS 
    WHERE 
     TC.ID = MS.ID 
    ORDER BY 
     TC.Type ASC 

第二存儲程序:

CREATE PROCEDURE B 
AS 
    SET NOCOUNT ON 

    SELECT DISTINCT 
     TC.*, MS.* 
    FROM 
     VIEW3 TC, 
     VIEW2 MS 
    WHERE 
     C.ID = MS.ID 
    ORDER BY 
     MS.Date DESC 

我想獲得這些2存儲過程的數據結果,然後將其綁定到gridview。我創建了以下存儲過程,但它引發ID列無效的錯誤:

CREATED PROCEDURE C 
AS 
    SET NOCOUNT ON 

    SELECT DISTINCT 
     TC.*, MS.* 
    FROM 
     (VIEW1 TC 
    LEFT JOIN 
     VIEW2 MS ON MS.ID = TC.ID) 

    UNION 

    SELECT DISTINCT 
     TC1.*, MS.* 
    FROM 
     (VIEW3 TC1 
    LEFT JOIN 
     VIEW2 MS on MS.ID = TC1.ID) 

如何組合2個存儲過程的數據結果?僅供參考,所有列都從視圖中選擇,而不是表格。

+0

是的我知道這一點,我檢查了它。並刪除了MySQL並標記爲SQL Server – ITDeveloper

+0

如果要使用UNION/UNION ALL組合數據集,這些數據集必須具有相同數量的列和數據類型(使用select *時這很危險),然後UNION運算符將強制數據排序以刪除重複項目(不確定是否計劃),然後考慮UNION ALL –

回答

0

如果你不想重複的代碼,然後創建一個結果表像

CREATE PROCEDURE C 
AS 
    CREATE TABLE #foo (bar int ...) 

    INSERT INTO #foo EXEC A 
    INSERT INTO #foo EXEC B 

    SELECT * FROM #foo 
    DROP TABLE #foo 

或只是統一的查詢,如果列具有類似的數據類型

CREATE PROCEDURE C 
AS 
    SELECT A.* FROM 
    (
     SELECT DISTINCT 
      TC.*,  MS.* 
     FROM 
      VIEW1 TC, 
      View2 MS 
     WHERE 
      TC.ID = MS.ID 
     ORDER BY 
      TC.Type ASC 
    ) A 
    UNION ALL 
    SELECT B.* FROM 
    (
     SELECT DISTINCT 
      TC.*, MS.* 
     FROM 
      VIEW3 TC, 
      VIEW2 MS 
     WHERE 
      C.ID = MS.ID 
     ORDER BY 
      MS.Date DESC 
    ) B 
2

在存儲過程中3號,你使用括號是錯誤的,它應該是這樣的

CREATE PROCEDURE C 
AS  
    SELECT DISTINCT 
     TC.*, MS1.* 
    FROM 
     VIEW1 TC 
    LEFT JOIN 
     VIEW2 MS1 ON MS1.ID = TC.ID 

    UNION 

    SELECT DISTINCT 
     TC2.*, MS2.* 
    FROM 
     VIEW3 TC2 
    LEFT JOIN 
     VIEW2 MS2 on MS2.ID = TC2.ID 

你也可以將存儲過程的結果插入臨時表中,然後顯示臨時表的結果:

CREATE TABLE #tempA(Column1 NVARCHAR(50),Column2 NVARCHAR(50),...) 

INSERT INTO #tempA (Column1, Column2, ...) 
EXEC A 

INSERT INTO #tempA (Column1, Column2, ...) 
EXEC B 

SELECT * FROM #tempA