如何在SQL Server 2008中比较两行?

时间:2014-01-06 08:59:49

标签: sql-server

我想逐列比较两行,它们看起来像这样:

    The rows 1,columns 1 compare to the other row 2,columns 1.
    The rows 1,columns 2 compare to the other row 2,columns 2.
    The rows 1,columns 3 compare to the other row 2,columns 3.
    The rows 1,columns 4 compare to the other row 2,columns 4.
    ........

逻辑将是:

if the rows 1 columns 1 equal to  rows 2,columns 1    
    do something
else    
    do other thing
.........

怎么做?

a. The two rows in the same table.
b. There are only two rows in the table

我想在程序中使用游标但无法访问它!谢谢!

1 个答案:

答案 0 :(得分:0)

试试这个 - 我希望这会对你有所帮助。我假设你的表中至少有两行(根据你的第三句话):

DECLARE cursor_name FOR
SELECT ID, Col1, Col2, Col3, Col4
FROM    [YOUR TABLE]
[YOUR WHERE CLAUSE HERE IF ANY]

OPEN cursor_name

DECLARE @CurID int
DECLARE @CurCol1 varchar(25)
DECLARE @CurCol2 varchar(25)
DECLARE @CurCol3 varchar(25)
DECLARE @CurCol4 varchar(25)

DECLARE @PrevID int
DECLARE @PrevCol1 varchar(25)
DECLARE @PrevCol2 varchar(25)
DECLARE @PrevCol3 varchar(25)
DECLARE @PrevCol4 varchar(25)

--Get First Row
FETCH NEXT FROM cursor_name 
INTO @PrevID, @PrevCol1, @PrevCol2, @PrevCol3, @PrevCol4

WHILE @@FETCH_STATUS = 0
BEGIN

    --Get Next Row
    FETCH NEXT FROM cursor_name 
    INTO @CurID, @CurCol1, @CurCol2, @CurCol3, @CurCol4

    --COMPARE
    IF @PrevCol1 = @CurCol1
        AND @PrevCol2 = @CurCol2
        AND @PrevCol3 = @CurCol3
        AND @PrevCol4 = @CurCol4
    BEGIN       
        --DO SOMTHING   
    END
    ELSE BEGIN
        --DO SOMETHING
    END

    --STORE CURRENT ROW
    SET @PrevCol1 = @CurCol1
    SET @PrevCol2 = @CurCol2
    SET @PrevCol3 = @CurCol3
    SET @PrevCol4 = @CurCol4

END

CLOSE cursor_name
DEALLOCATE cursor_name