CREATE function dbo.fn_SetBatchID
(@table as nvarchar(100)) returns char(11)
as
begin
DECLARE @BatchID AS char(11)
IF (select Count(*) from rtrim(ltrim(@table)))<>0 and DATEDIFF(day,cast(left((select max(BatchID) from rtrim(ltrim(@table))),8) as datetime),getdate())=0
begin
set @BatchID=(select max(BatchID) from rtrim(ltrim(@table)))
set @BatchID=cast((cast(@BatchID as bigint)+1) as char(11))
end
else
begin
set @BatchID=CONVERT(varchar(20),getdate(),112)+'001'
end
return @BatchID;
end
这个函数里面的@table变量是外部传递过来的数据表名,在下面的语句中执行,得到@BatchID变量值传回给函数,问题我将rtrim(ltrim(@table))这段换成实际的表名可以运行,但是如果用这个就报错,是不是不能这样写,应该怎么改呢?
有没有其他办法可以让函数用啊?过程用这个不太好。
我还准备提出各个表里面的BatchID之后,写以下语句呢:
insert table1
select test.dbo.fn_SetBatchID('table1'),* from table2