T-SQL查询检查存在的数量

时间:2010-02-13 19:28:05

标签: sql tsql sql-server-2008 stored-procedures

我有下一个近似的表结构:

accounts:
ID INT,
owner_id INT,
currency_id TINYINT

有关
clients:
ID INT

currency_types:
ID TINYINT,
name NVARCHAR(25)

我需要编写一个存储过程来检查具有特定货币和所有其他货币的账户是否存在,即客户可以拥有特定货币,其他一些货币和两者的账户。

我已经写过这个查询:

SELECT
    ISNULL((
    SELECT 1
    WHERE EXISTS
    (
        SELECT 1
        FROM [accounts] AS A, [currency_types] AS CT
        WHERE
            A.[owner_id] = @client -- sp param
        AND A.[currency_id] = CT.[ID]
        AND CT.[name] = N'Ruble'
    )), 0) AS [ruble],
    ISNULL((
    SELECT 1
    WHERE EXISTS
    (    
        SELECT A.[ID]
        FROM [accounts] AS A, [currency_types] AS CT
        WHERE
            A.[owner_id] = @client 
        AND A.[currency_id] = CT.[ID]
        AND CT.[name] != N'Ruble'
    )), 0) AS [foreign]

是否可以对其进行优化?我是(T)SQL的新手,所以提前感谢!

2 个答案:

答案 0 :(得分:1)

对我来说似乎很合理,EXISTS会为这类事情提供良好的表现。

您是否有理由认为需要优化?表现不好吗?

要确保的关键是你有合适的索引(例如账号。[owner_id],CT.ID显然是PK)

答案 1 :(得分:0)

此类查询需要少一个SELECT:

RETURN ISNULL((SELECT 1
    WHERE
        EXISTS
        (
            SELECT 1
            FROM [accounts] AS A, [currency_types] AS CT
            WHERE
                A.[owner_id] = @client 
            AND A.[currency_id] = CT.[ID]
            AND CT.[name] != N'Ruble'

        )
    ), 0)