/*自定义函数*/ create table myorder ( oid char(11) not null primary key, oname nvarchar(20) ) go insert myorder values(dbo.getid(),'aaaa') select * from myorder create function getid() returns char(11) as begin declare @result char(11) /* convert(char(8),getdate(),112):获取当前时间的前8位,如20170704 right(max(right(oid,3))+1001,3)获取后面三位的最大数 加上1001 然后取后面的三位数 */ select @result=convert(char(8),getdate(),112)+right(isnull (max(right(oid,3)),0)+1001,3) from myorder where left(oid,8)=convert(char(8),getdate(),112) return @result end