Store result in Variable

  • Hi,

    I would like to store the first "select" result into a variable to be able to declare it within the query


    declare @v_time datetime
    set @v_time = '1970-01-01 00:00:00'

    declare @v_date datetime
    set @v_date = '23-08-2018 00:00:00'

    declare @v_result bigint
    set @v_result = '1534982400' (the result of first select)

    SELECT cast(DATEDIFF(s, @v_time, @v_date) as bigint); Result: 1534982400
    SELECT DATEADD(s, 1534982400, @v_time)

    Thanks in advance,

    All help and Any help is appreciated

  • You mean?
    SET @v_result = cast(DATEDIFF(s, @v_time, @v_date) as bigint);

    Thom~

    Excuse my typos and sometimes awful grammar. My fingers work faster than my brain does.
    Larnu.uk

  • Thom A - Wednesday, September 5, 2018 4:36 AM

    You mean?
    SET @v_result = cast(DATEDIFF(s, @v_time, @v_date) as bigint);

    As easy as that!!

    Thanks it works perfectly, still loads to learn :'(

    All help and Any help is appreciated

  • Vitor da Fonseca - Wednesday, September 5, 2018 4:57 AM

    Thom A - Wednesday, September 5, 2018 4:36 AM

    You mean?
    SET @v_result = cast(DATEDIFF(s, @v_time, @v_date) as bigint);

    As easy as that!!

    Thanks it works perfectly, still loads to learn :'(

    Not to confuse you but as you may or may not learn there is more than 1 way to skin a ca...er um I mean populate a variable...
    assuming your datetime variables are formatted correctly (yours weren't)
    --This only populates the variable with a value again assuming other variable values are formatted correctly for your system
    SELECT @v_result=cast(DATEDIFF(s, @v_time, @v_date) as bigint); --Result: 1534982400
    --Let see the value
    PRINT @v_result

  • Vitor da Fonseca - Wednesday, September 5, 2018 4:22 AM

    Hi,

    I would like to store the first "select" result into a variable to be able to declare it within the query


    declare @v_time datetime
    set @v_time = '1970-01-01 00:00:00'

    declare @v_date datetime
    set @v_date = '23-08-2018 00:00:00'

    declare @v_result bigint
    set @v_result = '1534982400' (the result of first select)

    SELECT cast(DATEDIFF(s, @v_time, @v_date) as bigint); Result: 1534982400
    SELECT DATEADD(s, 1534982400, @v_time)

    Thanks in advance,

    Be careful of using a BIGINT here.  The DATEADD function requires the value to be convertable to an INT
    DATEADD (Transact-SQL)

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply