在做extjs开发时,界面grid的展示也是需要model(js)。这些model的数据最终肯定全部来自数据库,虽然不一定完全对应一张表,但是多数情况下,model字段与数据库几乎是完全对应的。当数据库表较多,表的字段也较多时,这时你才会意识到写一个sql脚本片断,能够自动拼接出Extjs的model的js脚本是多么省时的事!
用写程序生成extjs的model的方式也是可以的,也有人曾想过使用 Entity Framework等模板生成器来做。但个人认为还是没有直接写SQL片断来得快,而且同样是一劳永逸的事,快速方便。
-- @prefix是表的前缀的查询条件
declare @prefix varchar(50) = 'CMS_data_'
declare @table table(rownum int,tabelname varchar(50),fieldname varchar(50),type varchar(50))
insert into @table
select ROW_NUMBER() over(order by obj.name,column_id),obj.name tablename,col.name,
case when tp.name in('date','datetime','datetime2','smalldatetime') then 'date'
when tp.name in('int','bigint') then 'int'
when tp.name in('bit') then 'boolean'
when tp.name in('float','real','money','decimal','numeric','smallmoney') then 'float'
else 'string' end as [type]
from sys.all_columns col
left join sysobjects obj on obj.id = col.object_id
left join sys.types tp on tp.user_type_id = col.user_type_id
where xtype='U' and category=0 and obj.name like @prefix + '%'
select * from @table
declare @tablename varchar(50) = '',@lasttable varchar(50),@sql varchar(8000) = '',
@fieldname varchar(50),@type varchar(50)
declare @cur int = 1,@max int = (select COUNT(*) from @table),@tmpindex int = 0
while @cur <= @max
begin
select @tablename = tabelname,@fieldname = fieldname,@type = [type] from @table where rownum = @cur
--print @tablename + ',' + @fieldname
-- 初始化(第一行)
if @lasttable is null
begin
set @lasttable = @tablename
end
-- 处理输出
if @tablename <> @lasttable
begin
set @tmpindex = CHARINDEX('_',@lasttable,CHARINDEX('_',@lasttable,1) + 1)
print
'
/**
*@description ' + Stuff(@lasttable,1,@tmpindex,'') + '
*/
Ext.define(''' + @prefix + '.' + Stuff(@lasttable,1,@tmpindex,'') + 'Model'', {
extend: ''Ext.data.Model'',
fields: [' + STUFF(@sql,1,1,'') + '
]
});'
-- 重置状态
set @lasttable = @tablename
-- 清空@sql
set @sql = ''
end
-- 处理每一行数据
if @lasttable = @tablename
begin
set @sql += ',
{ name: "' + @fieldname + '", type: "' + @type + '" }'
if @lasttable is null
begin
set @lasttable = @tablename
end
end
--print @sql
set @cur += 1
end
-- 最后一张表的输出
if @sql is not null
begin
set @tmpindex = CHARINDEX('_',@lasttable,CHARINDEX('_',@lasttable,1) + 1)
print
'
/**
*@description ' + Stuff(@lasttable,1,@tmpindex,'') + '
*/
Ext.define(''' + @prefix + '.' + Stuff(@lasttable,1,@tmpindex,'') + 'Model'', {
extend: ''Ext.data.Model'',
fields: [' + STUFF(@sql,1,1,'') + '
]
});'
end