我有一個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...
沒有必要爲此使用循環。 –