在SQL Server中将YYYYMM格式转换为YYYY-MM-DD



我需要对一个具有索引的datetime列的大表执行查询。我们需要查询从一个月(至少)到多个月的数据。

这个查询将从CognosTM1执行,输入将是一个类似于YYYYMM的周期。我的问题是,如何将YYYYMM输入转换为可用于查询该表(使用索引)的格式。

假设输入是

  • 起始日期:'201312'
  • 截止日期:2013年12月

然后,我们需要在查询中将其转换为"2013年12月1日至2013年12日31日之间"

由于我们需要将其连接到CognosTM1中,因此无法编写过程或声明变量(TM1不知何故不喜欢它)。

提前感谢您的回复。

我会这样做:

create procedure dbo.getDataForMonth
  @yyyymm char(6) = null
as
  --
  -- use the current year/month if the year or month is invalid was omitted
  -- 
  set @yyyymm = case coalesce(@yyyymm,'')
                when '' then convert(char(6),current_timestamp,112)
                else         @yyyymm
                end
  --
  -- this should throw an exception if the date is invalid
  --
  declare @dtFrom date = convert(date,@yyyymm+'01') -- 1st of specified month
  declare @dtThru date = dateadd(month,1,@dtFrom)   -- 1st of next month
  --
  -- your Big Ugly Query Here
  --
  select *
  from dbo.some_table t
  where t.date_of_record >= @dtFrom
    and t.date_of_record < @dtThru
  --
  -- That's about all there is to it.
  --
  return 0
go

假设您在varchar变量@datefrom中获得YYYYMM的值。

你可以做一些类似的事情

DECLARE @DateFrom VARCHAR(6) = '201201';
-- Append '01' to any passed string and it will get all 
-- records starting from that month in that year
DECLARE @Date VARCHAR(8) = @DateFrom + '01'
-- in your query do something like 
SELECT * FROM TableName WHERE DateTimeColumn >= @Date

以ansi标准格式(即YYYYMMDD)传递Datetime是一个可搜索的表达式,它允许sql server利用在该日期时间列上定义的索引。

这是Rob Farley写的一篇关于SARGable functions in SQL Server的文章。

试试这个。。。

declare @startdate date,@endate date
select @startdate =convert(date,left('201312',4)+'-'+right('201312',2)+'-01')
select @endate= DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @startdate) + 1, 0))
select convert(date,@startdate,102) startdate,convert(date,@endate,102) endate

在TM1 Turbo Integrator进程的数据源中,您可以在SQL查询中使用参数。例如,您可以使用以下SQL查询:

SELECT Col1, Col2
FROM Table
WHERE Col1 = 'Green'
AND Col2 < 30

在TM1中,要将其参数化,您需要创建两个参数,例如P1和P2,并将它们放入查询中:

SELECT Col1, Col2
FROM Table
WHERE Col1 = '?P1?'
AND Col2 < ?P2?

最新更新