2015-05-29 48 views
0

我正在創建一個迴歸測試查詢,該查詢將檢查表是否被填充。這是通過獲取每個表A,B,C中的第一行並且如果它的ID存在,它將得到值「Y」。如果不是,則值「N」。我創建了下面的代碼來執行以下操作,但是我得到了語法錯誤:解析錯誤。有人可以告訴我什麼是錯的嗎?語法錯誤:解析錯誤,創建迴歸測試時檢查空表

SELECT 

Case 
    When EXISTS(A.Id) THEN 'Y' 
    ELSE 'N' 
END AS A_exist, 

Case 
    When EXISTS(B.Id) THEN 'Y' 
    ELSE 'N' 
END AS B_exist, 

Case 
    When EXISTS(C.Id) THEN 'Y' 
    ELSE 'N' 
END AS C_exist 

FROM 
(select top 1 * from Table_A) A 
(select top 1 * from Table_B) B 
(select top 1 * from Table_C) C 

回答

0

您可以強制使用空錶行中的COUNT

SELECT 
    CASE WHEN a.CNT = 1 THEN 'Y' ELSE 'N' END AS A_exist, 
    CASE WHEN b.CNT = 1 THEN 'Y' ELSE 'N' END AS B_exist, 
    CASE WHEN c.CNT = 1 THEN 'Y' ELSE 'N' END AS C_exist 
FROM 
(
    SELECT COUNT(*) AS CNT 
    WHERE EXISTS(SELECT * FROM Table_A) 
) AS a, 
(
    SELECT COUNT(*) AS CNT 
    WHERE EXISTS(SELECT * FROM Table_B) 
) AS b, 
(
    SELECT COUNT(*) AS CNT 
    WHERE EXISTS(SELECT * FROM Table_C) 
) AS c; 

但是你爲什麼不每個表返回一行而不是一列?延長要容易得多:

SELECT 'Table_A' AS "Table", CASE WHEN COUNT(*) = 1 THEN 'Y' ELSE 'N' END AS "Exists?" 
WHERE EXISTS(SELECT * FROM Table_A) 
UNION ALL 
SELECT 'Table_B', CASE WHEN COUNT(*) = 1 THEN 'Y' ELSE 'N' END 
WHERE EXISTS(SELECT * FROM Table_B) 
UNION ALL 
SELECT 'Table_C', CASE WHEN COUNT(*) = 1 THEN 'Y' ELSE 'N' END 
WHERE EXISTS(SELECT * FROM Table_C) 
+0

我給你第二個選擇,它完美的作品。謝謝! –

0

你使用sql-server嗎?這是否工作?

SELECT 

Case 
    When EXISTS(select * from Table_A) THEN 'Y' 
    ELSE 'N' 
END AS A_exist, 

Case 
    When EXISTS(select * from Table_B) THEN 'Y' 
    ELSE 'N' 
END AS B_exist, 

Case 
    When EXISTS(select * from Table_C) THEN 'Y' 
    ELSE 'N' 
END AS C_exist 
+0

嗨。我收到了子查詢中不支持TOP N的反饋。我正在使用Teradata。 –

0

您可以使用下面的查詢。

SELECT 

Case 
    When A.Id IS NOT NULL THEN 'Y' 
    ELSE 'N' 
END AS A_exist, 

Case 
    When B.Id IS NOT NULL THEN 'Y' 
    ELSE 'N' 
END AS B_exist, 

Case 
    When C.Id IS NOT NULL THEN 'Y' 
    ELSE 'N' 
END AS C_exist 

FROM 
(select top 1 * from Table_A) A, 
(select top 1 * from Table_B) B, 
(select top 1 * from Table_C) C 
; 
+0

這個解決方案的問題是,如果一個表爲空,那麼我不會得到值'N',而是整個reult集只是一個空表。我該如何解決這個問題? –

+0

在這種情況下,這個應該工作:SELECT 案例 當A.Id IS NOT NULL THEN 'Y' ELSE 'N' END AS A_exist, 'N' AS B_EXIST, 'N' AS C_exist FROM (選擇頂部1 *從表-A)甲 UNION SELECT 'N' AS A_EXIST, 案例 當B.Id IS NOT NULL THEN 'Y' ELSE 'N' END AS B_exist, 'N' AS C_EXIST FROM (從表B中選擇頂部1 *)B UNION SELECT 'N' AS A_EXIST, 'N' AS B_EXIST, 案例 當C.ID THEN IS NOT NULL 'Y' ELSE 'N' END AS C_exist FROM (選擇頂部1 *從Table_C)C ; –