[英]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
. 关键是我有一个名为MOSTEP
的表,该表中有一列称为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: 我需要检查表中所有MOID
的值,然后做2件事,条件的详细信息与该问题无关,因此我将其省略:
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. 我也在考虑在SELECT
中执行IF
或CASE
条件,但我不确定如何做到这一点。
If someone could help me I'll really appreciate it 如果有人可以帮助我,我将非常感激
Doesn't sound like there's any reason to use a cursor for this. 听起来好像没有理由为此使用游标。 You can use COUNT()
with OVER()
and CASE
efficiently: 您可以将COUNT()
与OVER()
和CASE
有效地结合使用:
;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 演示: SQL Fiddle
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.