存储过程:
USE [aaa]
GO
/****** Object: StoredProcedure [dbo].[John_getICMaxNum] Script Date: 04/29/2014 11:05:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: John
-- Create date: 2014-04-29
-- Description: 取t_Organization和t_Item应该填入的最大值
-- step 1: 取到t_Organization和t_Item现有的最大值
-- =============================================
ALTER PROCEDURE [dbo].[John_getICMaxNum]
@fTableName varchar(100),
@maxid int out
AS
DECLARE
@temp_id_1 int,
@temp_id_2 int
BEGIN
if (@fTableName='t_item' or @fTableName='t_Item')
begin
--step 1: 取t_Organization和t_Item现有最大值
select @temp_id_1=MAX(t3.FItemID) from (
select MAX(t1.FItemID) as FItemID
from t_Organization t1
union
select MAX(t2.FItemID) as FItemID
from t_Item t2
) t3;
--step 2: 取ICMaxNum现有最大值
SELECT @temp_id_2=FMaxNum
FROM ICMaxNum
where FTableName=@fTableName;
--step 3: 判断@temp_id_1+1与@temp_id_2的大小
if (@temp_id_1+1>@temp_id_2)
begin
update ICMaxNum set FMaxNum=@temp_id_1+1 where FTableName=@fTableName;
set @maxid=@temp_id_1+1;
end
else if (@temp_id_1+1<=@temp_id_2)
begin
set @maxid=@temp_id_2;
end
end
else
begin
SELECT @temp_id_2=FMaxNum
FROM ICMaxNum
where FTableName=@fTableName;
set @maxid=@temp_id_2;
end
select @maxid;
END
Hibernate调用:
public Integer getICMaxNum(String fTableName) {
StringBuffer temp_sb = new StringBuffer();
temp_sb.append("DBCC DROPCLEANBUFFERS; DBCC FREEPROCCACHE; set nocount on; begin transaction begin declare @maxid int,@ftablename varchar(100); ");
temp_sb.append("set @ftablename='"+fTableName+"'; ");
temp_sb.append("exec John_getICMaxNum @ftablename, @maxid out; select @maxid; end commit;");
log.info(temp_sb.toString());
Session session = this.sessionFactory.getCurrentSession();
Query query = session.createSQLQuery(temp_sb.toString());
List<Object> ol = query.list();
if (ol!=null && ol.size()!=0){
return Integer.valueOf(ol.get(0).toString());
}
return -1;
}