如何使用EXISTS条款的正确方法

时间:2016-12-02 23:47:28

标签: sql-server tsql stored-procedures exists

在我的SP中,我正在创建一个临时表#PolicyNumbers,并根据将提供给SP的参数使用Policy Numbers填充它。

CREATE TABLE #PolicyNumbers  (PolicyNumber varchar(50))
INSERT INTO #PolicyNumbers SELECT   PolicyNumber
                            FROM    PlazaInsuranceWPDataSet 
                            WHERE   State IN (SELECT * FROM [dbo].[StringOfStringsToTable](@State,','))  
                            AND Coverage IN (SELECT * FROM [dbo].[StringOfStringsToTable](@Coverage,','))
                            AND SICCode IN (SELECT * FROM [dbo].[StringOfStringsToTable](@SICCode,','))

在我的SP下面,我使用EXISTS语句来过滤那些 已根据参数选择PolicyNumber个。

WHERE   EXISTS (SELECT PolicyNumber FROM #PolicyNumbers pn WHERE pn.PolicyNumber = piwp.PolicyNumber)

因此#PolicyNumbers DOES的结果包含重复的PolicyNumbers:

enter image description here

然后在我的SP中找到了SELECT语句,结果还包含重复的PolicyNumber s:

SELECT 
            PolicyNumber,
            Cast(PolicyEffectiveDate AS DATE) AS PolicyEffectiveDate,
            Cast(PolicyExpirationDate AS DATE) AS PolicyExpirationDate,
            WrittenPremium
            FROM PlazaInsuranceWPDataSet

enter image description here

现在我正在使用EXIST声明:

SELECT 
        PolicyNumber,
        Cast(PolicyEffectiveDate AS DATE) AS PolicyEffectiveDate,
        Cast(PolicyExpirationDate AS DATE) AS PolicyExpirationDate,
        WrittenPremium
        FROM PlazaInsuranceWPDataSet piwp
        WHERE   EXISTS (SELECT PolicyNumber FROM #PolicyNumbers pn WHERE pn.PolicyNumber = piwp.PolicyNumber)

到目前为止一切都是正确的吗? 如果是,那么为什么我使用SELECT语句并使用IN(@MyParameter)在WHERE子句中传递相同的参数会略有不同?

SELECT 
            PolicyNumber,
            Cast(PolicyEffectiveDate AS DATE) AS PolicyEffectiveDate,
            Cast(PolicyExpirationDate AS DATE) AS PolicyExpirationDate,
            WrittenPremium
            FROM PlazaInsuranceWPDataSet piwp
            WHERE    State IN (@State) 
                    AND SICCode IN (@SICCode)
                    AND Coverage IN (@Coverage)

1 个答案:

答案 0 :(得分:2)

两个查询之间的区别在于,第一个获取的是一个策略编号列表,其中表中至少有一行与StateSICodeCoverage匹配。由于PlazaInsuranceWPDataSet中有多个行,并且每个行可以有不同的StateSICodeCoverage(大概),这与仅选择{{1}中的行不同在那三个谓词上匹配。

这是一个简化的例子:

PlazaInsuranceWPDataSet

政策编号行中的一行(且只有一行)' A'匹配条件,所以当我们在临时表中记下该政策号码,然后与之比较时,我们将获得所有的行' A'回来。