Windowed function in update

  • Hi,

    Is it possible to do this:

    update stg_PAreporting

    set [jobname] = [jobname] + '-' + cast(row_number() over (partition by [jobname] order by [date]) as varchar(3))

    I want to append -1, -2, -3 etc to the end of the job name depending on how many times it shows up in the table ordered by oldest date to newest.

    It works fine in a select:

    select [jobname],[jobname] + '-' + cast(row_number() over (partition by [jobname] order by [date]) as varchar(3))

    from stg_PAreporting

    but with an update, it fails. "Windowed functions can only appear in the SELECT or ORDER BY clauses."

    Is there a solution for this?

    Thanks much,

    Howard

  • Hi can you post some DDL with some test data, I think I know a way to do this but I'd like to verify it with your data if possible.

    http://sqlvince.blogspot.com/[/url]

  • Assuming ID is the PK of stg_PAreporting:

    WITH JobOrder

    AS

    (

    SELECT ID

    jobname

    ,jobname + '-' + CAST(ROW_NUMBER() OVER (PARTITION BY jobname ORDER BY [date]) AS varchar(3)) AS NewJobName

    FROM stg_PAreporting

    )

    UPDATE JobOrder

    SET jobname = NewJobName

  • Thanks for the responses.

    I am always really happy to learn something new. Using CTE, there is a lot that can be accomplished.

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

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