1

SQL Server 2008 相关问题

我有一张表记录了申请信用卡的人

CREATE TABLE [dbo].[CREDITCARD_APPLICATION](
    [CREDITCARD_APPLICATION_ID] [bigint] IDENTITY(1,1) NOT NULL,
    [PRIMARY_CUSTOMER_ID] [int] NOT NULL,
    [SECONDARY_CUSTOMER_ID] [int] NULL,
    [PRIMARY_CARD_ID] [int] NULL,
    [SECONDARY_CARD_ID] [int] NULL,
    [STORE_ID] [int] NULL,
    [CARD_REFERRAL_SOURCE] [nvarchar](50) NULL,
    [CAMPAIGN_CODE] [varchar](30) NULL,
    [CREATED_DATE] [datetime2](3) NOT NULL,
    [CREATED_BY] [varchar](50) NOT NULL,
    [LAST_MODIFIED_DATE] [datetime2](3) NULL,
    [LAST_MODIFIED_BY] [varchar](50) NULL,
    [VERSION] [timestamp] NOT NULL
    )

我还有一个连接到这个表的视图,其中包含卡片和客户。我需要从该表中获取一条信息,即campaign_code,并且我在视图中通过使用coalesce嵌套选择来执行此操作。

SELECT....some data....
    ,coalesce((SELECT TOP 1 CAMPAIGN_CODE FROM dbo.CREDITCARD_APPLICATION cca where     cca.PRIMARY_CARD_ID=cc.card_id ORDER BY cca.CREATED_DATE DESC),
        (SELECT TOP 1 CAMPAIGN_CODE FROM dbo.CREDITCARD_APPLICATION cca     where cca.SECONDARY_CARD_ID=cc.card_id ORDER BY cca.CREATED_DATE DESC))

  AS LatestCampaignCode 

我想知道的是 2 个 select 语句是否将始终执行,或者如果它从第一个语句中找到结果,它将在那里停止处理。总是执行这些选择似乎有点低效,事实上在很多(大多数)情况下,表中不会有任何匹配的记录

4

1 回答 1

1

Yes, I believe it's going to execute both queries (with around 90% confidence), but not necessarily as you have them.

I don't know exactly what it does, but I would guess that it's going to go get all the information from the primary query, then it's going to execute something similar to a join on the second query using data from the first. then it will go execute the third query similar to a join using only the rows that still had null values. But it's up to the optimizer how to do it, and it may actually pull the data in a way that is different than how your sql statement is intended to flow.

What I said will make more sense if you go look at the execution plan. A few things that I will say that may make things a bit more clear as well.

  1. COALESCE is just turns into a CASE statement, and thus the same rules apply as a case statement
  2. The query you have could likely be turned into joins instead of correlated sub-queries and I would expect that the query analyzer / optimizer will do just that and that is in-fact how it's being executed.
于 2013-05-23T22:51:24.080 回答