我使用的是SQL Server,需要根据租户ID保留一个会计编号。
我无法使用自动增量ID,因为它是按顺序递增的,并且在客户端应用程序中存在间隙。
我无法使用计算列作为ArrayList<String> EnglishCategorie = new ArrayList<String>();
EnglishCategorie.add("HarryPotter");
boolean repeatAgain = true;
while(repeatAgain) {
System.out.println("Please choose an option (between 1 and 5) :");
System.out.println("Press 1 to search a book in English Categorie.
System.out.println("Press 2 to exit the program. "); ");
int choice = input.nextInt();
switch (choice) {
case 1:
System.out.println("Please enter a book name: ");
bookName = input.nextLine();
if(bookName == EnglishCategorie.contains("HarryPotter") )
System.out.println("It is available.");
else
System.out.println("It is not available.");
break;
之类的聚合函数
最好的办法是什么?
答案 0 :(得分:3)
您还可以在插入数据时进行处理,例如:
insert into table1(ID,TenantId,PaymentId)
select 6,2,isnull(max(PaymentId)+1,1)
from table1 where TenantId=2
group by TenantId
如果你想使用触发器,这是一个示例,在该示例中,即使您在插入数据时指定了PaymentId,此触发器也会重新计算PaymentId
DROP TABLE table1
CREATE TABLE Table1(ID INT IDENTITY(1,1),TenantId INT ,PaymentId INT)
CREATE TRIGGER trg_UpdatePaymentId
ON dbo.TABLE1
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
UPDATE t SET t.PaymentId=a.rn
FROM dbo.TABLE1 AS t INNER JOIN (
SELECT i.ID,(ISNULL(c.MaxPaymentId,0)+ ROW_NUMBER()OVER(PARTITION BY TenantId ORDER BY ID)) AS rn FROM Inserted AS i
OUTER APPLY(
SELECT MAX(tt.PaymentId) AS MaxPaymentId FROM Table1 AS tt WHERE tt.TenantId=i.TenantId AND NOT EXISTS(SELECT 0 FROM Inserted AS ii WHERE ii.ID=tt.ID)
) AS c
) AS a ON a.ID=t.ID
END
GO
INSERT INTO table1(TenantId)VALUES(1),(2),(1),(1)
SELECT * FROM dbo.TABLE1
ID TenantId PaymentId ----------- ----------- ----------- 1 1 1 2 2 1 3 1 2 4 1 3