Search code examples
sqlsql-server-2008-r2cursor

Not sure if I should use a cursor in Microsoft SQL Server 2008 R2


I have a problem here. The thing is that I have a table called MOSTEP, in this table there's a column called MOID. What I need to do is to check repeated values, what I mean by this is for example, in the table there are these values:

10, 9, 8, 6, 9, 5, 2 10

I need to check all the values of MOID in the table and then do 2 things, the details of the conditions are rather irrelevant to this questions so I'll omit them:

  1. if the value only appears once, I do something with each of them.
  2. If the value appears more than once, I do something else with each of them.

I know how to check for repeated and not repeated values using

COUNT(MOID)

However I don't know how to check for this in a same query and make it efficient.

I was thinking in using two cursors, one that stores all the repeated values and then just fetch each row, and another that does the same thing but with the non repeated values. But I've heard that cursors are not always the best option

I was also thinking in doing IF or CASE conditions within a SELECT but I'm not really sure how of to do it.

If someone could help me I'll really appreciate it


Solution

  • Doesn't sound like there's any reason to use a cursor for this. You can use COUNT() with OVER() and CASE efficiently:

    ;WITH cte AS (SELECT *,COUNT(MOID) OVER(PARTITION BY MOID) MOID_CT
                  FROM MOSTEP)
    SELECT MOID
          ,CASE WHEN MOID_CT = 1 THEN 'Something' ELSE 'SomethingElse' END
    FROM cte
    

    Demo: SQL Fiddle