使用单个存在查询检查多个表是否存在?

时间:2013-09-20 19:52:46

标签: sql sybase exists

我有类似的东西 -

IF EXISTS (SELECT 1 FROM systable st
                JOIN sysuserperm sup ON st.creator = sup.user_id
                WHERE sup.user_name = 'TEST'
                AND st.table_type = 'BASE'
                AND st.table_name = 'Table1') THEN
IF EXISTS (SELECT 1 FROM systable st
                JOIN sysuserperm sup ON st.creator = sup.user_id
                WHERE sup.user_name = 'TEST'
                AND st.table_type = 'BASE'
                AND st.table_name = 'Table2') THEN

在一个存在中将多个这些组合在一起的最佳方法是什么?

3 个答案:

答案 0 :(得分:1)

试试这个,

SELECT  1 
FROM    systable st
        INNER JOIN sysuserperm sup 
            ON st.creator = sup.user_id
WHERE   sup.user_name = 'TEST' AND 
        st.table_type = 'BASE' AND 
        st.table_name IN ('Table1', 'table2')
GROUP   BY sup.user_name, st.table_type
HAVING  COUNT(DISTINCT st.table_name) = 2

答案 1 :(得分:0)

更多行会更快:

IF EXISTS (SELECT TOP 1 1 FROM systable st
                JOIN sysuserperm sup ON st.creator = sup.user_id
                WHERE sup.user_name = 'TEST'
                AND st.table_type = 'BASE'
                AND st.table_name in ('Table1', 'Table2')) THEN

答案 2 :(得分:0)

这应该完成任务

IF EXISTS (
    (SELECT 1 FROM INFORMATION_SCHEMA.Tables WHERE TABLE_NAME='TABLE1') 
    INTERSECT
    (SELECT 1 FROM INFORMATION_SCHEMA.Tables WHERE TABLE_NAME='TABLE2')
)