无参存储过程转参数形式出现问题
--2. 无参存储过程最流水号
create proc GetMaxNo @itemNo varchar(20) output
as
set nocount on
declare @maxNo varchar(20),@i int
set @maxNo='CD'+replace(convert(varchar(10),getdate(),120),'-','')
select @i=isnull(max(right(itemNo,4)),0)+1 from tb where itemNo like @maxNo+'%'
set @maxNo=@maxNo+right('000'+cast(@i as varchar),4)
set @itemNo=@maxNo
return
go
--新增时调用
declare @itemNo varchar(20)
exec GetMaxNo @itemNo output
insert into tb(itemNo) values(@itemNo)
有参数存储过程
create proc GetMaxNo @itemNo varchar(20) output,
@biaoshi varchar(10),
@table varchar(20),
@ziduan varchar(20)
as
set nocount on
declare @maxNo varchar(20),@i int
set @maxNo=@biaoshi+replace(convert(varchar(10),getdate(),120),'-','')
select @i=isnull(max(right(@ziduan,4)),0)+1 from @table where @ziduan like @maxNo+'%'
set @maxNo=@maxNo+right('000'+cast(@i as varchar),4)
set @itemNo=@maxNo
return
go
提示的提示错误是:消息 1087,级别 16,状态 1,过程 GetMaxNo,第 10 行
必须声明表变量 "@table"。
ALTER proc GetMaxNo @itemNo varchar(20) output,
@biaoshi varchar(10),
@table varchar(20),
@ziduan varchar(20)
as
set nocount on
declare @maxNo varchar(20),@i INT, @sql NVARCHAR(max)
set @maxNo=@biaoshi+replace(convert(varchar(10),getdate(),120),'-','')
SET @sql = N'select @i=isnull(max(right(@ziduan,4)),0)+1 from '+ QUOTENAME(@table) +' where @ziduan like @maxNo+''%'''
PRINT @sql
EXEC sp_executesql @sql, N'@i int output, @ziduan varchar(20), @maxNo varchar(20)', @i OUTPUT, @ziduan, @maxNo
SET @maxNo=@maxNo+right('000'+cast(@i as varchar),4)
set @itemNo=@maxNo
return
GO
create proc GetMaxNo
(@itemNo varchar(20) output,
@biaoshi varchar(10),
@table varchar(20),
@ziduan varchar(20))
as
begin
set nocount on
declare @maxNo varchar(20),@i int,@tsql nvarchar(4000)
set @maxNo=@biaoshi+replace(convert(varchar(10),getdate(),120),'-','')
select @tsql=N'select @i=isnull(max(right('+@ziduan+',4)),0)+1 from '+@table+' where '+@ziduan+' like '''+@maxNo+'%'' '
exec sp_executesql @tsql,N'@i int output',@i=@i output
set @maxNo=@maxNo+right('000'+cast(@i as varchar),4)
set @itemNo=@maxNo
end
go