创建SQL视图,用实际变量替换变量对我来说不起作用

时间:2010-06-27 05:25:28

标签: sql views

首先,我要感谢您的帮助!

现在我将查询转换为SQL中的视图,因此我需要将所有变量替换为实际值。但是,这样做我遇到了麻烦。

当我有

    DECLARE @TweleveAM datetime
    set @TweleveAM = '1900-01-01 00:00:00'
    DECLARE @TweleveThirtyAM datetime
    set @TweleveThirtyAM = '1900-01-01 00:30:00'

    WHEN (cast(segstart as float) - floor(cast(segstart as float))) >= 
(cast(@TweleveAM as float) - floor(cast(@TweleveAM as float))) 
and (cast(segstart as float) - floor(cast(segstart as float))) < 
(cast(@TweleveThirtyAM as float) - floor(cast(@TweleveThirtyAM as float)))
THEN CAST('0' as int)

而我使用

    WHEN (cast(segstart as float) - floor(cast(segstart as float))) >= 
(cast(cast('1900-01-01 00:00:00' as datetime)as float) - 
floor(cast(cast('1900-01-01 00:00:00' as datetime) as float))) 
and (cast(segstart as float) - floor(cast(segstart as float))) < 
(cast(cast('1900-01-01 00:00:30' as datetime) as float) - 
floor(cast(cast('1900-01-01 00:00:30' as datetime) as float)))
THEN CAST('0' as int)


ELSE Null End as Interval

我的查询产生Null,实际上数据永远不会为NULL。

我在这里做错了什么?

2 个答案:

答案 0 :(得分:3)

我同意马克认为这可以简化。尽管如此,回答你的问题。 这两个版本不一样。最上面的

 DECLARE @TweleveThirtyAM datetime
    set @TweleveThirtyAM = '1900-01-01 00:30:00'

第二个人在午夜过后有30秒

'1900-01-01 00:00:30'

尽管你应该使用ISO格式1900-01-01T00:30:00.000。在查询中替换的正确值类似于

SELECT
  CASE
    WHEN
      (
        CAST(segstart AS FLOAT) - floor(CAST(segstart AS FLOAT))
      )
      >= (CAST(CAST('1900-01-01T00:00:00.000' AS DATETIME) AS FLOAT) - floor(CAST(CAST('1900-01-01T00:00:00.000' AS DATETIME) AS FLOAT)))
    AND
      (
        CAST(segstart AS FLOAT) - floor(CAST(segstart AS FLOAT))
      )
      < (CAST(CAST('1900-01-01T00:30:00.000' AS DATETIME) AS FLOAT) - floor(CAST(CAST('1900-01-01T00:30:00.000' AS DATETIME) AS FLOAT)))
    THEN CAST('0' as int)
    ELSE NULL
  END AS Interval
FROM T

这可以简化为

SELECT
  CASE
    WHEN
      (
        CAST(segstart AS FLOAT) - floor(CAST(segstart AS FLOAT))
      )
      >= 0
    AND
      (
        CAST(segstart AS FLOAT) - floor(CAST(segstart AS FLOAT))
      )
      < 1.0/48
    THEN 0
    ELSE NULL
  END AS Interval
FROM T

我不认为第一部分可能是假的,因此可以删除

SELECT
  CASE
    WHEN
        CAST(segstart AS FLOAT) - floor(CAST(segstart AS FLOAT)) < 1.0/48
    THEN 0
    ELSE NULL
  END AS Interval
FROM T

可能更清楚

SELECT
  CASE
    WHEN
        DATEPART(HOUR, segstart) = 0 AND DATEPART(MINUTE, segstart  < 30)
    THEN 0
    ELSE NULL
  END AS Interval
FROM T

另外(并且更具推测性)除非半小时对您的申请具有特殊意义,我想知道这是否是一个更大的案例陈述的一部分,将一天分为48个半小时间隔?如果是这样,这可能会起到作用。

SELECT 2 * DATEPART(HOUR, segstart) +  DATEPART(MINUTE, segstart) / 30 AS Interval

答案 1 :(得分:1)

看起来你正在使用SQLServer。我建议不要将日期时间转换为浮点数来计算时间差,而是建议在适当时使用SQLServer的datediff函数和分钟或秒参数。