带声明的sql视图

时间:2014-07-25 20:21:04

标签: sql sql-server view

我在视图中需要这个,但似乎你不能使用声明。 帮助

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

4 个答案:

答案 0 :(得分: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可能正在进行一些过滤。但它可能会有效地解决您的问题。

答案 1 :(得分: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()

答案 2 :(得分: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

答案 3 :(得分:0)

如果您需要参数,性能和在您的视图中声明语句,然后下面的替代方案可能值得考虑。

另一种方法是将视图中的逻辑包装到创建表的存储过程中。 PROC可以截断&amp;更新或删除&amp;重新创建表格。如果您的表很大,您还可以在表上创建索引。

如果你需要在很多地方调用视图/表,你可以将它包装在一些更新表的逻辑中,如果满足某些条件。例如仅每天更新一次表或每30分钟更新一次等。

可以理解,这可能会产生代码开销,因为在每次使用视图之前,您需要检查是否需要更新。但结果是yopu

希望有所帮助。