当前位置: 代码迷 >> Sql Server >> 存储过程!1
  详细解决方案

存储过程!1

热度:22   发布时间:2016-04-27 16:25:08.0
求一个存储过程!在线等!!1
表结构:
create   table   test(
                      pkid   int   identity(1,1)   primary   key,
                      date_id   varchar(50)
)
实现这样的功能,
先检查某表记录是否为空(不是某一具体的表,但表的结构是一样的,如上),如为空,在表中插入一条记录,该记录的值为系统时间加上编码0001,比如是今天的,该表又为空,那么返回的date_id的值就为200705260001(注意:这里就是这样的格式,不是类似于2007-05-26-001,或2007/05/26/0001的格式),
如果检查某表的记录不为空,刚先比较年份是否是当年,即前四位是否是2007,如果是的话,再检查是否是当月,即检查是否是05(不是的话,则05加1变成06,相应的天数就取系统当天的日再加上编码001);如果某表中有记录,并且年月日都和当天的系统时间相对应。那么就在后面的编码上加1
-----------------------
想写一个生成单据编号的存储过程,可以是进货时,也可以是出货时,所以表是动态的应该。编号=年+月+日+编码(从0001开妈)
也就比如说每要生成一个单据时,些单据的编号就会在表中去检查上次的编号来比较进而产生这次的编号,如果表中就没记录则就把系统时间+(从0001开始的编码)返回过去!  
--------
说了好长,不知道大家看明白了没,   在线等   谢谢!!

------解决方案--------------------

create table test(
pkid int identity(1,1) primary key,
date_id varchar(50)
)

create proc pc(
@date nvarchar(8),
@re nvarchar(12) output
)
as
begin
if exists(select * from test where charindex(@re,date_id)=1)
begin
select @date=max(date_id) from test where charindex(@re,date_id)=1
set @[email protected]+1
end
else
begin
set @[email protected]+ '0001 '
insert test(date_id) values(@date)
end
end

------解决方案--------------------
--上面的错了改改吧

create table test(
pkid int identity(1,1) primary key,
date_id varchar(50)
)

create proc pc(
@date nvarchar(12),
@re nvarchar(12) output
)
as
begin
if exists(select * from test where charindex(@date,date_id)=1)
begin
select @date=max(date_id) from test where charindex(@date,date_id)=1
set @re=left(@date,8)+right( '0000 '+rtrim(right(@date,4)+1),4)
end
else
begin
set @[email protected]+ '0001 '
end

insert test(date_id) values(@re)
end


declare @re nvarchar(12)
declare @date nvarchar(8)
set @date=convert(nvarchar(8),getdate(),112)
exec pc @date,@re output

select * from test
------解决方案--------------------
先建立一个视图(如果表不是如态增加的)
SELECT object_id( 'Table1 ') AS tid, Tab_id
FROM dbo._Sp_test
UNION
SELECT object_id( 'Table2 ') AS tid, Tab_id
FROM dbo._net_test
union
.....
如视图名为AllTabId
再建立存储过程
Create PROCEDURE dbo.test
(@Name varchar(50),
@Date smalldatetime
)

AS
declare @sql varchar(200)
if not exists(select date_id from AllTabId where tid=object_id(@Name))
begin
set @sql= 'insert ' + @Name + ' (date_id) Values ( ' ' ' + convert(varchar(8),GetDate(),112) + '0001 ' ') '
execute(@sql)
end
else
begin
declare @num varchar(12)
select @num = convert(int,max(right(date_id,4))) +1 from AllTabId where tid=object_id(@Name) and date_id like convert(varchar(8),@date ,112) + '% '
set @num= convert(varchar(8),@date ,112) + replicate( '0 ',4-len(@num)) + convert(varchar(4),@num)
set @sql = 'insert ' + @Name + ' (date_id) values ( ' ' ' + @num + ' ' ') '
execute(@sql)
end
  相关解决方案