我需要一些存儲的特效轉換爲視圖和存儲的特效有很多,其創建得到在隨後的查詢中引用常量DECLARE
語句。例如如何在查詢中多次引用SQL代碼片段?
SELECT @FIRSTDAYLASTYEAR = DATEADD(YEAR, DATEDIFF(YEAR, '1901-01-01', DATEADD(YEAR, -1, getdate())), '1901-01-01')
我需要多次指@FIRSTDAYLASTYEAR
在一個查詢中,有什麼要做到這一點,而不必聲明變量的最佳方式?
例如考慮:
DECLARE @FIRSTDAYLASTYEAR datetime = DATEADD(YEAR, DATEDIFF(YEAR, '1901-01-01', DATEADD(YEAR, -1, getdate())), '1901-01-01')
select
@FIRSTDAYLASTYEAR as FirstDayLastYear,
Case when orderDate > @FIRSTDAYLASTYEAR then 'CurrentOrders' else 'ArchiveOrders' end as State
from
orders
我不想改寫爲
select
DATEADD(YEAR, DATEDIFF(YEAR, '1901-01-01', DATEADD(YEAR, -1, getdate())), '1901-01-01') as FirstDayLastYear,
Case when orderDate > DATEADD(YEAR, DATEDIFF(YEAR, '1901-01-01', DATEADD(YEAR, -1, getdate())), '1901-01-01') then 'CurrentOrders' else 'ArchiveOrders' end as State
from
orders
我希望能夠別名@FIRSTDAYLASTYEAR
某種方式查詢。
編輯
感謝您的答覆,你覺得這會執行相同的:
select
constants.FirstDayLastYear,
Case when orderDate > constants.FirstDayLastYear then 'CurrentOrders' else 'ArchiveOrders' end as State
from
orders o
cross join
(select
DATEADD(YEAR, DATEDIFF(YEAR, '1901-01-01', DATEADD(YEAR, -1, getdate())), '1901-01-01') as FirstDayLastYear
) as constants
原因我問的是,這種代碼可能會被移植到另一個數據庫平臺,在未來某一日期不支持CTE。
@RaduGheorghiu - 因爲意見必須是一個'SELECT'聲明。 –