admin

SQL Server中的等效收益率

sql

我在SQL Server(DWH)中写下视图,用例伪代码为:

-- Do some calculation and generate #Temp1
-- ... contains other selects

-- Select statement 1
SELECT * FROM Foo
JOIN #Temp1 tmp on tmp.ID = Foo.ID
WHERE Foo.Deleted = 1

-- Do some calculation and generate #Temp2
-- ... contains other selects

-- Select statement 2
SELECT * FROM Foo
JOIN #Temp2 tmp on tmp.ID = Foo.ID
WHERE Foo.Deleted = 1

该视图的结果应为:

Select Statement 1
UNION
Select Statement 2

预期的行为与yield returnC#中的行为相同。有没有办法告诉视图哪些SELECT语句实际上是结果的一部分,哪些不是结果的一部分?因为在我需要的内容之前的少量计算也包含selects。

谢谢!


阅读 150

收藏
2021-06-07

共1个答案

admin

我找到了更好的解决方法。这可能对其他人有帮助。实际上是将所有计算都包含在WITH语句内部,而不是在视图核心中执行它们:

WITH Temp1 (ID)
AS
(
    -- Do some calculation and generate #Temp1
    -- ... contains other selects
)

, Temp2 (ID)
AS
(
    -- Do some calculation and generate #Temp2
    -- ... contains other selects
)

-- Select statement 1
SELECT * FROM Foo
JOIN Temp1 tmp on tmp.ID = Foo.ID
WHERE Foo.Deleted = 1

UNION

-- Select statement 2
SELECT * FROM Foo
JOIN Temp2 tmp on tmp.ID = Foo.ID
WHERE Foo.Deleted = 1

结果当然UNION是所有外围SELECT声明的结果。

2021-06-07