sql语句从数据库中检索最后一个条目值

时间:2013-07-19 12:07:39

标签: sql sql-server

我的自动号码有两部分

3位数是序列号,最后8位是发票的月份和年份

例如:001072013

所以,如果我想要下一个InvoiceNo

我从数据库中的发票编号的最后一个条目中选择,如此

select TOP 1 InvoiceNo 
from BuyInvoice

剪切前3位数字,然后进行增量,并将其与发票的月份和年份相结合

所以它会是002072013

问题是上面的语句没有返回最后一个条目值

并且升序和降序都不起作用

4 个答案:

答案 0 :(得分:2)

我会尝试:

select TOP 1 InvoiceNo 
from BuyInvoice order by right(InvoiceNo,4) desc,
  right(InvoiceNo, 6) desc, 
  InvoiceNo desc

答案 1 :(得分:0)

试试这个

select TOP 1 InvoiceNo 
  from BuyInvoice order by InvoiceNo desc

答案 2 :(得分:0)

我假设BuyInvoice表格的InvoiceDate列具有与date列的InvoiceNo部分相同的值。在此我会使用的情况(解决方案未经过测试):

DECLARE @InvoiceDate DATE;
SET @InvoiceDate='2013-07-20';

BEGIN TRANSACTION;

DECLARE @LastInvoiceNo VARCHAR(9);

SELECT TOP(1) @LastInvoiceNo=bi.InvoiceNo 
-- This table hint (UPDLOCK) take a U lock on this row[s] so any concurrent [similar] transactions will have to wait till this transaction is finished
-- This will prevent duplicated new InvoiceNo 
FROM dbo.BuyInvoice bi WITH(UPDLOCK) 
WHERE bi.InvoiceDate=@InvoiceDate
ORDER BY bi.InvoiceNo DESC;

DECLARE @Seq SMALLINT;
SET @Seq=ISNULL(CONVERT(SMALLINT,LEFT(@LastInvoiceNo,3)),0);
SET @Seq=@Seq+1;

DECLARE @NewInvoiceNo VARCHAR(9);
SET @NewInvoiceNo=RIGHT('00'+CONVERT(VARCHAR(3),@Seq),3)+STUFF(STUFF(CONVERT(VARCHAR(10),@InvoiceDate,101),3,1,''),5,1,''); -- Convert style 101 = mm/dd/yyyy

...

INSERT dbo.BuyInvoice(InvoiceNo,InvoiceDate,...)
VALUES (@NewInvoiceNo,@InvoiceDate,...);
...

COMMIT TRANSACTION;

此外,我会使用BEGIN TRY ... END CATCH拦截异常并在需要时回滚此事务(link:示例B)。

另外,我将创建以下索引:

-- This way, the InvoiceNo column will have uniques values
CREATE UNIQUE INDEX IUN_BuyInvoice_InvoiceNo
ON dbo.BuyInvoice(InvoiceNo);
GO
-- This index is used by SELECT TOP(1) ... query
CREATE UNIQUE INDEX IN_BuyInvoice_InvoiceDate_InvoiceNo
ON dbo.BuyInvoice(InvoiceDate,InvoiceNo);
GO

答案 3 :(得分:0)

select top 1 InvoiceNo from BuyInvoice order by left(InvoiceNo,3) desc