0

我正在使用无法更改表格的 3rd pary 应用程序。我们使用附加的日期时间列“AsOfDate”构建了自定义匹配的“每月”表,我们在其中转储了月末的数据,并将这些数据标记为当月最后一天的日期。

我希望能够创建单个存储过程(应用程序旨在要求视图或存储过程作为所有报告的来源。)并使用将使用当前数据表的参数(参数可能为 NULL 或 = Today's日期)或使用月末表并按月末日期过滤。这样,我有一个报告,用户可以使用当前或特定月末期间的数据。

你更喜欢哪个(以及为什么)对不起,这不是完全编码的

解决方案 #1 联合查询

Create Proc Balance_Report (@AsOfDate)
AS

Select Column1
From
    (Select GetDate() as AsOfDate
       , Column1 
     From Current.Balance
    Union 
    Select AsOfDate
       , Column1 From MonthEnd.Balance
    ) AS All_Balances
Where All_Balances.AsOfDate = @AsOfDate

解决方案 #2 使用 If 语句选择表

Create Proc Balance_Report (@AsOfDate)
AS

If @AsOfDate IS NULL or @AsOfDate = GetDate()
   Select GetDate() as AsOfDate
       , Column1 
     From Current.Balance
Else
    Select AsOfDate
       , Column1 From MonthEnd.Balance
    Where AsOfDate = @AsOfDate

同样,这不是完全编码的,并且与数据库无关(但它是 SQL Server 2005)。

编辑:使用单独的存储过程对解决方案 #2 的变体

Create Proc Balance_Report (@AsOfDate)
AS

If @AsOfDate IS NULL or @AsOfDate = GetDate()
   Exec Current_Balance_Date -- no param necessary
Else
    exec MonthEnd_Balance_Date @AsOfDate
4

2 回答 2

1

我更喜欢非工会的解决方案。从单个表中选择总是比进行联合并从联合中选择单个表的数据要快。

于 2009-02-07T13:08:56.300 回答
1

您如何设置,第二种方法可能会更快。如果您要使用分区视图,那么您可以设置约束,使优化者知道忽略选择中的一个或多个表,并且您将获得相同的性能。这也可以让您将所有逻辑保存在一个语句中,而不必让两个语句保持同步。根据 SELECT 语句的复杂程度,这对您来说可能是也可能不是问题。

One thing to remember though, is that if you use the second method, be sure to mark your stored procedure as WITH (RECOMPILE) (I can't remember if the parentheses are require or not - check the syntax). That way the optimizer will create a new query plan based on which branch of the IF statement needs to be executed.

于 2009-02-07T13:41:26.563 回答