while循环后SQL表变量为空

时间:2016-02-23 21:23:59

标签: sql-server

我有一个SQL表,我正在尝试查询唯一结果。基于“FileName”列,我想只获取每个文件名的最新行。 在示例中,我将使用姓氏“smith”提取所有文件。 LoanNumber可能在多行中,因为文件可能已被复制,因此我只想要最新的文件。

以下代码不会产生任何数据。我只得到一个名为“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]=@ThisLoanNumber Order By [UpdateTime] Desc;
    END;
CLOSE LoanFiles;
DEALLOCATE LoanFiles;
Select * from @ResultsTable;                        --display results...

1 个答案:

答案 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