2014-07-25 67 views
1

我需要這個視圖,但它似乎你不能使用聲明。 有幫助嗎?聲明的SQL視圖

declare @lastsat datetime 
set @lastsat = 
(select max(fechahoy) from [BigArea].[Thing].[Expanded] where DiaSemana='Saturday') 

SELECT a.*, 
case 
when b.fecha_gestion = a.fechahoy and month(fechahoy)!=month(getdate()) then 1 
when a.fechahoy = @lastsat then 1 
else 0 
end as FinDeMEs 
    FROM [BigArea].[Thing].[Expanded] a 
    join [BigArea].[dbo].[fechas_gestion] b 
    on a.fechahoy = b.fecha 
+0

根據T-SQL的用法和非標準引用添加了'sql-server'標籤'[..]' –

+3

你可能不應該公開地發佈模式,包括用戶名和類似.... – Dan

回答

0

難道你不能只是改變你的SQL,以避免變量聲明?

SELECT a.*, 
case 
    when b.fecha_gestion = a.fechahoy and month(fechahoy)!=month(getdate()) then 1 
    when a.fechahoy = (select max(fechahoy) from [AreaComercial].[LARRA_DOM\Mpollak].[Canales_expandida] where DiaSemana='Saturday') 
    then 1 
    else 0 
end as FinDeMEs 
FROM [AreaComercial].[LARRA_DOM\Mpollak].[Canales_expandida] a 
join [AreaComercial].[dbo].[fechas_gestion] b on a.fechahoy = b.fecha 
2

出於性能方面的原因,我會傾向於join在值:

select e.*, 
     (case when g.fecha_gestion = e.fechahoy and month(fechahoy) <> month(getdate()) then 1 
      when e.fechahoy = m.fechahoy then 1 
      else 0 
     end) as FinDeMEs 
from [AreaComercial].[LARRA_DOM\Mpollak].[Canales_expandida] e join 
    [AreaComercial].[dbo].[fechas_gestion] g 
     on e.fechahoy = g.fecha cross join 
     (select max(fechahoy) as fechahoy 
     from [AreaComercial].[LARRA_DOM\Mpollak].[Canales_expandida] 
     where DiaSemana = 'Saturday' 
    ) m; 

我也建議你使用表縮寫表的別名。

順便說一句,你也許可以用窗函數代替邏輯:

select e.*, 
     (case when g.fecha_gestion = e.fechahoy and month(fechahoy) <> month(getdate()) then 1 
      when e.fechahoy = max(case when e.diasemana = 'Saturday' then e.fechahoy end) 
      then 1 
      else 0 
     end) as FinDeMEs 
from [AreaComercial].[LARRA_DOM\Mpollak].[Canales_expandida] e join 
    [AreaComercial].[dbo].[fechas_gestion] g 
     on e.fechahoy = g.fecha; 

這不是100%保證,因爲join可以做一些篩選。但它很可能有效地解決您的問題。

2

您可以創建一個表值函數,然後把你的查詢中,並在視圖中選擇它,

CREATE FUNCTION FUNCTION_NAME () 
RETURNS @retContactInformation TABLE 
(
-- YOUR COUMN DEFINATIONS HERE 
) 
AS 

    declare @lastsat datetime 
set @lastsat = 
(select max(fechahoy) from [AreaComercial].[LARRA_DOM\Mpollak].[Canales_expandida] where DiaSemana='Saturday') 

SELECT a.*, 
case 
when b.fecha_gestion = a.fechahoy and month(fechahoy)!=month(getdate()) then 1 
when a.fechahoy = @lastsat then 1 
else 0 
end as FinDeMEs 
    FROM [AreaComercial].[LARRA_DOM\Mpollak].[Canales_expandida] a 
    join [AreaComercial].[dbo].[fechas_gestion] b 
    on a.fechahoy = b.fecha 

GO 

然後在您的視圖:

SELECT * FROM FUNCTION_NAME() 
0

如果您需要的參數,性能&在您的視圖中聲明陳述,那麼下面的替代方案可能值得考慮。

另一種替代方法是將您的視圖中的邏輯封裝到創建表的存儲過程中。 PROC可以截斷&更新或刪除&重新創建表。如果你的表很大,你也可以在表上創建索引。

如果您需要在很多地方調用視圖/表,可以將它包裝在某些滿足某些條件的情況下更新表的邏輯中。例如只能每天更新一次表格或每30分鐘更新一次等。

可以理解的是,這可能會造成代碼開銷,因爲在每次使用視圖之前,您需要檢查是否需要更新視圖。但結果是,yopu

希望有所幫助。