IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[sys_sql_genvars]') AND type = 'P')
DROP PROCEDURE [dbo].[sys_sql_genvars]
GO

create procedure [dbo].[sys_sql_genvars](
@script varchar(max) output
)as
begin
declare @varname varchar(50),@datatype varchar(20),@fldsize int,@fldprec int,@isstring int,@i int,@varDef varchar(50)
 ,@cnt int ,@s varchar(50),@lineCnt int
 select  @cnt = 0,@i=0,@script = '',@lineCnt = 0
 
Declare vars Cursor local static  For
select varname,datatype,fldsize,fldprec
from flatVarDef
OPEN vars
Fetch next from vars into @varname,  @datatype, @fldsize,@fldprec
While (@@Fetch_status=0)
begin --1.1
set @varDef=@varname

set @i=charindex('char',@datatype)
if (@i>0)
set @datatype='string'

if (@datatype is null)
set @datatype='string'


if (@datatype='varchar')
set @datatype='string'

if (@fldsize is null)
set @fldsize=20
if (@fldprec is null)
set @fldprec=2
 
select @isString=0
--整数
set @i=charindex('bigint',@datatype)
if (@i>0)
select @varDef = @varDef + ' bigint' 
else 
begin
set @i=charindex('int',@datatype)
if (@i>0)
select @varDef = @varDef + ' int' 
end
 
set @i=charindex('date',@datatype)
if (@i>0)
select @varDef = @varDef + ' datetime' 

set @i=charindex('decimal',@datatype)
if (@i>0)
begin --1.1.3
select @s=convert(varchar(2),@fldprec)
if (@s is null)
set @s='2'
select @varDef = @varDef + ' decimal(18,' + @s+ ')' 
end --end 1.1.3

set @i=charindex('string',@datatype)
if (@i>0)
begin --1.1.4
select @isString=1 --缺省为字符串型

if (@fldsize is null or @fldsize<2)
set @fldsize=50

select @s=convert(varchar(4),@fldsize)
if (@s is null)
set @s='50'
select @varDef = @varDef +   ' nvarchar(' + @s+ ')' 
end --end 1.1.4
if (@varDef is null)
goto nxt

if (@cnt=0)
select @script = '  Declare ' + @varDef
else
select @script = @script +',' + @varDef
if (@lineCnt=5)
begin
set @lineCnt=0
select @script = @script + char(13) + '  '
end
else
select @lineCnt=@lineCnt+1

select @cnt = @cnt + 1
nxt:
Fetch next from vars into @varname,  @datatype, @fldsize,@fldprec
end --end 1.1

 select @script=@script +char(13)

end