使用CTE的SQL脚本

时间:2015-01-05 06:30:35

标签: sql sql-server tsql

我在下面使用CTE查询。我想知道是否有一些方法除此之外。所以我正在收集一些建议来重构它。有任何建议请。或者查询看起来是否正常,即使我在查询中多次使用此IN (SELECT InvariantLanguageCultureCode FROM y)语句?

DECLARE  @ReportingInstanceID INT

SET @ReportingInstanceID=34
;WITH x AS (
    SELECT  [dbo].[tenant_Reporting_Instance].UserID
    FROM    [dbo].[tenant_Reporting_Instance]
    WHERE   tenant_Reporting_Instance.ReportingInstanceID = @ReportingInstanceID
), y AS ( 
    SELECT  [TRCCore].[dbo].[pr_Language].InvariantLanguageCultureCode
    FROM    [TRCCore].[dbo].[pr_Language]
    JOIN [dbo].[tenant_User_Setting] 
        ON tenant_User_Setting.LanguageID = pr_Language.LanguageID
    WHERE   tenant_User_Setting.UserID IN (
                SELECT UserID FROM x
    )
), Default_User_Settings_CTE ( RoundingTypeInvariantCode, AgingDateValue
                             , CurrencyLabel, JobZoneLinkTypeLabel, MatchPeriodLabel
                             , PayFrequencyLabel, PayTypeLabel )
    AS ( SELECT   r.RoundingTypeInvariantCode ,
                  a.AgingDateValue ,
                  cur.CurrencyLabel ,
                  jz.JobZoneLinkTypeLabel ,
                  m.MatchPeriodLabel ,
                  pf.PayFrequencyLabel ,
                  pt.PayTypeLabel
         FROM     dbo.tenant_User_Setting s
         JOIN TRCCore.dbo.pr_Rounding_Type r 
             ON r.RoundingTypeID = s.RoundingTypeID
         JOIN dbo.tenant_Aging_Date a 
             ON a.AgingDateID = s.AgingDateID
         JOIN TRCCore.dbo.translation_pr_Currency cur 
             ON cur.CurrencyID = s.CurrencyID
             AND cur.LanguageCultureCode IN ( SELECT InvariantLanguageCultureCode 
                                              FROM y)
         JOIN dbo.translation_tenant_Job_Zone_Link_Type jz 
             ON jz.JobZoneLinkTypeID = s.JobZoneLinkTypeID
             AND jz.LanguageCultureCode IN (  SELECT InvariantLanguageCultureCode 
                                              FROM y)
         JOIN dbo.tenant_Match_Period m 
             ON m.MatchPeriodID = s.MatchPeriodID
         JOIN dbo.translation_tenant_Pay_Frequency pf 
             ON pf.PayFrequencyID = s.PayFrequencyID
             AND pf.LanguageCultureCode IN (SELECT InvariantLanguageCultureCode 
                                            FROM y)
         JOIN dbo.translation_app_Pay_Type pt 
             ON pt.PayTypeID = s.PayTypeID
             AND pt.LanguageCultureCode IN (SELECT InvariantLanguageCultureCode 
                                            FROM y)
         WHERE    s.UserID IN (SELECT UserID FROM x)
    )
    SELECT * FROM Default_User_Settings_CTE

1 个答案:

答案 0 :(得分:0)

将查询结果填充到临时表中,以便可以根据需要多次重复使用。