2014-01-06 64 views
0

我想列兩行進行比較,它們看起來就像這樣:如何比較SQL Server 2008中的兩行?

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 

我想在程序中使用光標,但無法訪問它!謝謝!

+4

「我想使用遊標」 - 也許是這樣,但你可能*不應該*。此表中只有*兩行嗎?還是有*行*對? (如何識別這些對?)。或者應該將每一行與「前一行」進行比較? (在這種情況下,什麼定義了「previous」的定義?)或者這些行在不同的表中? (在這種情況下,我們如何在表格之間配對?) –

+1

繼續編輯您的問題,因爲它仍然不明確 – Leo

回答

0

試試這個 - 我希望這可以幫助你。我假設表中至少有2行(基於你的第三句話):

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 
+0

謝謝,我沒有更好的解決方案。我會像你說的那樣做! – user3127259