Comparing Values in the Same Column

  • I'm working on a problem where I need to compare values in the same column. Example. I have int field with values 123,123,123 for 3 different records. I want to capture that first value and compare it to the second, if the value is the same then I will do some math, if that value is different I want to capture it and compare it to the next and so on. This is a one time script to cleanup some data. I'm looking at cursors, declaring varibles, case statements but nothing is working. Can any one help?

  • Of course this is a problem in procedural programing, not batch programing. Thus, this is the kind of code that makes DBAs (like me) tense up and make ugly faces. With that being said, assuming that you have a unique index, I believe you want something like this:

    declare @id int

    declare @newvalue int

    declare @oldvalue int

    select @id = min([UNIQUE INDEX])

    from

    while @id is not null

    Begin

    select @newvalue = [COLUMN]

    from

    where [UNIQUE INDEX] = @id

    if @newvalue = @oldvalue

    Begin

    --Your Code Here

    End

    select @oldvalue = @newvalue

    select @id = min([UNIQUE INDEX])

    from

    where [UNIQUE INDEX] > @id

    End

Viewing 2 posts - 1 through 1 (of 1 total)

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