【问题标题】:Regarding this SQL query, how can I output list of 28/30/31 days according to user's choice of certain month and year关于这个 SQL 查询,如何根据用户选择的特定月份和年份输出 28/30/31 天的列表
【发布时间】:2018-07-07 15:52:54
【问题描述】:

我已经在这里声明了所有变量。

    declare @FromDate as datetime;
    declare @ToDate as datetime;
    declare @OperID as varchar(20) = 'OP1';
    declare @Year as int = 2018
    declare @Month as int = 1

 set @FromDate = convert(date,convert(varchar,@Year) + '-' + 
    convert(varchar,@Month) + '-01')
    set @ToDate = dateadd(d,-1,DATEADD(m, 1, @FromDate))

这是查询的主体,我要输出 Branch_No,operid 是 Staff ID,Clock_date 是时钟 In 和时钟 Out 的日期,[I] 代表时钟输入, [O] 代表时钟输出。

    select Branch_no, operid, clock_date, [I], [O]
    from
    ( select Branch_no, operid, 
    convert(date, clock_date) as clock_date, 
    convert(time, clock_date) as clock_time, 
    clock_type, Workstation_no
    from ROSTER_TIMECLOCK
    where Clock_date >=CONVERT(DATETIME, @FromDate, 102)
    and Clock_date <=CONVERT(DATETIME, @ToDate, 102)
    and OperID=@OperID  ) as TheClock

然后,我使用 Pivot 组合查询以显示这样的列中的数据

分行编号 |时钟日期 |员工证 |输入 |出局

   PIVOT
  ( min(clock_time)
  FOR clock_type in ([I],[O])
  ) as ThePivot 

The Table

【问题讨论】:

  • 您的意思是输出日期是从 1 到 28 还是 30 或 31,无论您的表中是否有这些日期的条目?
  • 我的意思是,2 月 1 日至 28 日,基本上它遵循所选月份有多少天,假设用户选择 1 月和 2018 年,那么它将列出所有天数月。

标签: sql vb.net stored-procedures


【解决方案1】:

创建一个包含所选期间所有日期的临时表,然后在输出表上执行左连接,如下所示:

Create procedure nameofsp
@year int,
@month int
As

declare @FromDate as datetime
declare @ToDate datetime
declare @OperID varchar( 20 )  

set @FromDate = convert(datetime,convert(varchar,@Year) + '-' + 
    convert(varchar,@Month) + '-01')
    set @ToDate = dateadd(d,-1,DATEADD(m, 1, @FromDate))

--  create a table that contains all the dates for the period selected
declare @dates table( currentdate datetime )
;with cte( curr )
as
(
    select @fromdate
    union all
    select dateadd( d, 1, curr )
        from cte 
        where curr < @todate
)
insert into @dates( currentdate )
    select curr
        from cte

select a.CurrentDate, 
        b.operId, 
        b.Branch_No,
        b.I, 
        b.O 
    from @dates a 
    left outer join @inout b on b.clock_date = a.currentdate 
    order by a.currentdate, b.i 

【讨论】:

  • 先生,它正在工作,谢谢,但有一个问题,我应该在存储过程/查询中放置哪些变量?我的意思是,如果用户、月份和年份不同,我该如何控制?
  • 将它们作为 sql 参数传递给您的存储过程。传递年份和月份。
  • 好的,先生,已经通过了,但是我应该在这个查询中把月份、年份和 operID 放在哪里?谢谢。
【解决方案2】:
Create procedure procname
@year int,
@month int
As
(Rest of the code goes here)

去掉年月的声明。

【讨论】:

  • 先生,我怎样才能用变量替换“插入@inout”和不同月份、年份和operID的内容?谢谢
猜你喜欢
  • 2017-01-08
  • 2018-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-03
相关资源
最近更新 更多