简体   繁体   English

T-SQL SELECT TOP值和增量

[英]T-SQL SELECT TOP Value and increment

I'm currently working on a stored procedure in SQL Server 2012. I have the following table: 我目前正在使用SQL Server 2012中的存储过程。我具有下表:

Id | SalesAreaId | CollectionId 
---+-------------+-----------
1  |     12      |     1
2  |     7       |     1
3  |     5       |     1

I want to select the highest CollectionId and increment it +1. 我想选择最高的CollectionId并将其增加+1。

DECLARE @CollectionId INT = 1;

SELECT TOP 1 @CollectionId = [CollectionId]
FROM [MyProject].[Sales]
WHERE [CollectionId] = MAX([CollectionId])

@CollectionId = @CollectionId + 1

As a result the next @CollectionId should be 2, unfortunately this doesn't really work... 结果,下一个@CollectionId应该为2,不幸的是这实际上并没有用...

Do you have an idea on how to solve this issue? 您是否有解决此问题的想法?

Thank you very much! 非常感谢你!

Just write this as: 只需将其写为:

SELECT @CollectionId = MAX([CollectionId])
FROM [MyProject].[Sales];

Normally, you would do the increment in the SELECT and take into account an empty table: 通常,您将在SELECT进行递增, 考虑一个空表:

SELECT @CollectionId = COALESCE(1 + MAX([CollectionId], 1)
FROM [MyProject].[Sales];
DECLARE @CollectionId INT = 1;
SELECT @CollectionId  = ((SELECT MAX(CollectionId) FROM [MyProject].[Sales])+1);    

increments the last collectionid with one if the last collectionid is the largest of all collectionids 如果最后一个collectionid是所有collectionid中最大的一个,则将最后一个collectionid加1。

You can SELECT simply as follows 您可以简单地选择如下

SELECT TOP 1 (CollectionId + 1)
FROM Sales
ORDER BY CollectionId DESC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM