使用连接检查约束不适用于查询/视图

时间:2019-05-28 16:39:09

标签: sql-server

我们有如下描述的视图:

CREATE view [dbo].[PriceHourlyView]
AS
select NodeId, TimeStamp,RtDa,MarketId,Lmp,Mlc,Mcc,Issettledprice,datecreated,IsCalculated from dbo.PriceHourly WITH (NOLOCK)
union all
select NodeId, TimeStamp,RtDa,MarketId,Lmp,Mlc,Mcc,Issettledprice,datecreated,IsCalculated from dbo.PriceHourly2018 WITH (NOLOCK)
union all
select NodeId, TimeStamp,RtDa,MarketId,Lmp,Mlc,Mcc,Issettledprice,datecreated,IsCalculated from dbo.PriceHourly2017 WITH (NOLOCK)
union all
select NodeId, TimeStamp,RtDa,MarketId,Lmp,Mlc,Mcc,Issettledprice,datecreated,IsCalculated from dbo.PriceHourly2016 WITH (NOLOCK)
union all
select NodeId, TimeStamp,RtDa,MarketId,Lmp,Mlc,Mcc,Issettledprice,datecreated,IsCalculated from dbo.PriceHourly2015 WITH (NOLOCK)
union all
select NodeId, TimeStamp,RtDa,MarketId,Lmp,Mlc,Mcc,Issettledprice,datecreated,IsCalculated from dbo.PriceHourly2014 WITH (NOLOCK)
union all
select NodeId, TimeStamp,RtDa,MarketId,Lmp,Mlc,Mcc,Issettledprice,datecreated,IsCalculated from dbo.PriceHourly2013 WITH (NOLOCK)
union all
select NodeId, TimeStamp,RtDa,MarketId,Lmp,Mlc,Mcc,Issettledprice,datecreated,IsCalculated from dbo.PriceHourly2012 WITH (NOLOCK)

除未指定年份的当前表外,每个表每年都有如下检查约束:

ALTER TABLE [dbo].[PriceHourly2017]  WITH CHECK ADD  CONSTRAINT [CK_PriceHourly2017_Timestamp] CHECK  (([timestamp]>='2017-01-01' AND [timestamp]<='2017-12-31 23:59'))

当该视图本身被查询时,检查约束将限制正在搜索的表。执行计划如下:

SELECT
  *
FROM PriceHourlyview
WHERE nodeid = 24511
AND TimeStamp BETWEEN '2017-05-17' AND '2017-05-24'

Correct check constraints

现在,当我在时间戳字段上加入该表时,查询不再使用检查约束,而是使用每个表来检查数据。

SELECT
  *
FROM ShapeProfileDetails s WITH (NOLOCK)
LEFT JOIN PriceHourlyView p WITH (NOLOCK)
  ON s.TimeStamp = p.Timestamp
  AND s.EffectiveDate BETWEEN '2017-05-17' AND '2017-05-24'
WHERE NodeId = 24512
--AND s.EffectiveDate BETWEEN '2017-05-17' AND '2017-05-24'

Incorrect check constraints

我知道我没有在连接的示例中查询相同的字段,并假设这是问题所在,但这是我需要查询正确结果的字段。我想知道是否有任何提示或强制查询使用正确的检查约束。或者尝试加入并使用这些检查约束的最佳实践是什么。

1 个答案:

答案 0 :(得分:1)

好的,正如我们所讨论的,我们知道EffectiveDateTimeStamp几乎相同。我会尝试做这样的事情。从技术上讲,这是相同的查询,但是我们会让SQL Server知道它可以使用约束(只需在BETWEEN的边缘减去并加1天)。

SELECT * FROM ShapeProfileDetails s WITH (NOLOCK) 
JOIN PriceHourlyView p WITH (NOLOCK) 
   ON s.TimeStamp = p.Timestamp 
AND s.EffectiveDate BETWEEN '2017-05-17' AND '2017-05-24' 
AND s.TimeStamp BETWEEN '2017-05-16' AND '2017-05-25' 
WHERE NodeId = 24512