1

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

该查询将从 Cognos TM1 执行,输入将是一个句点,如YYYYMM. 我的问题是 - 如何将YYYYMM输入转换为可用于查询该表的格式(使用正在使用的索引)。

假设输入是

  • 从日期:'201312'
  • 迄今为止:'201312'

然后,我们需要在查询中将其转换为“在 01-12-2013 和 31-12-2013 之间”

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

提前感谢您的回复。

4

4 回答 4

1

假设您YYYYMM在 varchar 变量 @datefrom 中获取此值。

你可以做类似的事情

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 标准格式传递 Datetime 即YYYYMMDD是一个 sargable 表达式,并允许 sql server 利用在该 datetime 列上定义的索引。

这是Rob Farley写的一篇关于SARGable functions in SQL Server.

于 2014-10-15T23:31:47.027 回答
1

我会做这样的事情:

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
于 2014-10-15T23:48:49.630 回答
0

尝试这个...

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
于 2014-10-16T01:43:31.033 回答
0

在 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?
于 2014-11-23T06:14:35.073 回答