5 thoughts on “Question of the Week -08/04/2014

  1. Bharat Narang

    create proc techmixing_8_4_14 @yr as numeric
    as
    SET NOCOUNT ON;
    set datefirst 1 — to set first day as monday

    declare @dt as varchar(8);
    declare @count as numeric=1
    create table #t1 (mn varchar(20)) — Temporary table
    while @count <=12
    begin

    set @dt=convert(varchar(4),@yr ) + isnull(REPLICATE('0',2-len(convert(varchar(2),@count))),'')+convert(varchar(2),@count)+ '01'

    set @count=@count+1
    if datepart(dw,convert(date,@dt,112 )) >=6
    begin
    insert into #t1 (mn) select datepart(MM,@dt)
    end

    end
    select * from #t1

    go

    exec techmixing_8_4_14 2012

    Reply
    1. Bharat Narang

      To get month name, we can also replace datepart with datename in below statement :

      insert into #t1 (mn) select datepart(MM,@dt)

      Reply
  2. admin Post author

    Just to little modify the Bharat answer by adding "No count off" in the end.

    Create proc techmixing_8_4_14 @yr as numeric
    as
    begin
    SET NOCOUNT ON;
    set datefirst 1 — to set first day as monday

    declare @dt as varchar(8);
    declare @count as numeric=1
    create table #t1 (mn varchar(20)) — Temporary table
    while @count <=12
    begin

    set @dt=convert(varchar(4),@yr ) + isnull(REPLICATE('0',2-len(convert(varchar(2),@count))),'')+convert(varchar(2),@count)+ '01'

    set @count=@count+1
    if datepart(dw,convert(date,@dt,112 )) >=6
    begin
    insert into #t1 (mn) select datename(MM,@dt)
    end

    end
    select * from #t1
    set nocount off
    end
    go

    exec techmixing_8_4_14 2012

    Reply
  3. Soumya Joe

    Declare @Months Varchar(60)

    Declare @loop int
    SET @loop=1

    WHILE @loop<=12
    BEGIN
    IF(Datename(dw,'2014/'+str(@loop)+'/1') in ('Saturday','Sunday'))
    BEGIN
    SET @Months=COALESCE(@Months+ ', ', '')+ DateName( month , DateAdd( month , @loop , 0 ) -1)
    END
    SET @loop=@loop+1
    END

    Print @Months

    Reply

Leave a Reply