2016-02-23 43 views
0

我有一個SQL表我試圖查詢唯一結果。基於「FileName」列,我只想得到每個文件名的最近行。 在這個例子中,我拉着姓氏爲「smith」的所有文件。 LoanNumber可能在多行,因爲該文件可能已被複制,所以我只想要最近的一個。while循環後SQL表變量爲空

下面的代碼不帶有任何數據。我只得到一個名爲「FileID」的列標題並且沒有值。我相信@ResultsTable並沒有保留我想用第12行INSERT語句寫入的數據。我不知道爲什麼。我試着移動表變量@ResultsTable的DECLARE語句,並且最好的是我可以讓它顯示的是單個記錄和我放置的大部分地方,我只會得到「必須聲明表變量」@ResultsTable「。」

我在做什麼錯誤,表變量沒有得到正確填充和維護它的行?

DECLARE @ResultsTable table(FileID varchar(10)); --table variable for the list of record IDs 

DECLARE @ThisLoanNumber varchar(50);    --current loan number for each record to be used during while loop 
DECLARE LoanFiles CURSOR read_only FOR    --create LoanFiles cursor to loop through 
Select distinct [LoanNumber] from [Package_Files] 
Where [LastName]='smith'; 
OPEN LoanFiles; 

While @@FETCH_STATUS = 0       --If previous fetch was successful, loop through the cursor "LoanFiles" 
    BEGIN 
     FETCH NEXT FROM LoanFiles into @ThisLoanNumber; --Get the LoanNumber from the current row 
     INSERT Into @ResultsTable     --insert the ID number of the row which was updated most recently of the rows which have a loan number equal to the number form the current row in "LoanFiles" cursor 
     Select Top 1 [iFileID] From [Package_Files] Where [LoanNumber][email protected] Order By [UpdateTime] Desc; 
    END; 
CLOSE LoanFiles; 
DEALLOCATE LoanFiles; 
Select * from @ResultsTable;      --display results... 
+0

沒有必要爲此使用循環。 –

回答

1

有幾種方法可以做這種類型的查詢而不訴諸循環。

這是使用cte。

with SortedValues as 
(
    select FileID 
     , ROW_NUMBER() over (partition by LoanNumber order by UpdateTime desc) as RowNum 
    from Package_Files 
    where LastName = 'Smith' 
) 
select FileID 
from SortedValues 
where RowNum = 1 

另一種選擇是使用類似於此的子查詢方法。

select FileID 
from 
(
    select FileID 
     , ROW_NUMBER() over (partition by LoanNumber order by UpdateTime desc) as RowNum 
    from Package_Files 
    where LastName = 'Smith' 
) x 
where x.RowNum = 1 
+0

超級簡單...謝謝。我最喜歡CTE版本。我不知道「ROW_NUMBER()」函數。 – Michael

+1

如果這對你有用,那麼你應該考慮將其標記爲答案。 –

+2

你的意思是說派生表,而不是子查詢。 –