2015-06-22 43 views
0

我經常使用此查詢來檢索與數據庫中的字符串匹配的所有列。我試圖鏈接兩個表,並且爲此我需要匹配列來連接兩個表。在SQL數據庫的表中查找兩列

我希望能夠搜索是具有字符串「CUSTOMER_ID」,並以「WORKORDER_BASE_ID」

另一列一列的表中有一個簡單的方法來做到這一點,從這個sqript工作?我認爲某種類型的子查詢可能是必要的,但我還沒有做任何工作。

SELECT 
    t.name AS table_name 
    ,SCHEMA_NAME(schema_id) AS schema_name 
    ,c.name AS column_name 
    ,T.modify_date 
FROM sys.tables AS t 
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID 
WHERE 
    c.name LIKE '%CUSTOMER_ID%'          
ORDER BY modify_date 
+4

'從...選擇*,其中c.name IN( 'CUSTOMER_ID', 'workorder_base_id'),其具有COUNT(*)= 2'? –

+1

@MarcB說什麼(除了沒有'SELECT *') – Lamak

回答

1

像這樣的東西應該工作:

SELECT t.name AS table_name , 
     SCHEMA_NAME(schema_id) AS schema_name , 
     c.name AS column_name , 
     T.modify_date 
FROM sys.tables AS t 
     INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID 
WHERE EXISTS (SELECT * 
       FROM sys.columns c1 
       WHERE c1.object_id = c.object_id 
         AND c1.name = 'CUSTOMER_ID') 
     AND EXISTS (SELECT * 
        FROM sys.columns c1 
        WHERE c1.object_id = c.object_id 
          AND c1.name = 'WORKORDER_BASE_ID') 
ORDER BY modify_date 
+0

這工作!謝謝。 – mreff555