Better approach of conditional column query

安稳与你 提交于 2019-12-13 18:06:50

问题


--OldQuery
SELECT oldStartDate AS column,...
FROM Table
WHERE
oldStartDate > @date,...
GROUP BY
oldStartDate,...

There is a new column newStartDate nullable added to the table and data extraction has to be conditionally depending on this column

--NewQuery
SELECT ISNULL(newStartDate, oldStartDate) AS column,...
FROM Table
WHERE
(    
    (newStartDate IS NULL AND oldStartDate > @date)
    OR 
    (newStartDate > @date)
),...
GROUP BY
ISNULL(newStartDate, oldStartDate),...

Above is the approach I can think of to retrieve conditionally however it seems to me will cause performance issue and I can't evaluate in DEV environment as volume is not big enough but production is estimating roughly 2mil records. Wondering if there is any other recommended approach instead?


回答1:


If you are going to use ISNULL in the GROUP BY clause you might as well also use in in the WHERE clause, since both would make the newStartDate un sargable, because the column is nullable. (Thanks for the link, John Cappelletti!)

Assuming the NewStartDate will replace the OldStartDate, one thing you can do to is update all the null values in newStartDate to the non-null values of oldStartDate, and then alter your newStartDate column as a non-nullable column:

UPDATE TableName
SET NewStartDate = OldStartDate
WHERE NewStartDate IS NULL;
GO

ALTER TABLE TableName
    ALTER COLUMN NewStartDate date NOT NULL;
GO

Then your query can be much simpler and sargable:

SELECT NewStartDate AS column,...
FROM Table
WHERE
NewStartDate > @date,...
GROUP BY
NewStartDate ,...


来源:https://stackoverflow.com/questions/49105875/better-approach-of-conditional-column-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!