将表中字段面设置为Get,Set属性值-MS SQL Server存储过程(较通用)

作者在 2008-08-05 09:58:17 发布以下内容

工作中经常会碰到将表中字段名设置为get{;}set{;}这种情形,所以为了方便,当然要写一个通用的代码,对于这篇文章这标题也不知道怎么取好.

主要功能例如:
表a(A1 int,A2 varchar)
执行该存储过程后结果出现
private int a1
public int A1
{
get{return a1;}
set{a1=value;}
}

private string a2;
public string A2
{
   get{return a2;}
   set{a2=value;}
}
其实就是能自动生成属性的代码,这样就不用再自己设置属性值了,当然对于表字段类型还没有完全罗列齐全,所以类型适用一bigint,int,varcha,datetime
自己可以完善这个代码
设置属性的存储过程代码:
--exec GetSet 'AutoTool'

create proc [dbo].[GetSet](@Table varchar(100))
As
begin

-----------Declare column name and column type
declare @name varchar(100)
declare @type varchar(50)
-----------------申明游标------------
declare cursor_type cursor for
select [name],
case
when user_type_id=127 then 'long'
when user_type_id=167 or user_type_id=35 then 'string'
when user_type_id=56 then 'int'
when user_type_id=61 then 'DateTime' end [type]    
from sys.columns C
where exists(
select 1 from sys.objects o where [type]='U' AND [Name]=@Table AND o.[object_id]=c.[object_id]
)
declare @mark int
declare @sql varchar(max)
---------初始化变量----------
set @sql=''
set @mark=0

open cursor_type
fetch next from cursor_type into @name,@type
while(@@fetch_status=0)
begin

    if(@mark=1)
      set @sql=@sql+' union all '
--------开始将字段名逐个设置为Get,Set属性值-------------
    set @sql=@sql+'select ''private '+@type+' '+Lower(@name)+';'''
    set @sql=@sql+' union all '
    set @sql=@sql+'select ''public '+@type+' '+@name+''''
    set @sql=@sql+' union all '
    set @sql=@sql+'select ''{'''
    set @sql=@sql+' union all '
    set @sql=@sql+'select '' get{return '+Lower(@name)+';}'''
    set @sql=@sql+' union all '
    set @sql=@sql+'select '' set{'+Lower(@name)+'=value;}'''
    set @sql=@sql+' union all '
    set @sql=@sql+'select ''}'''
    set @mark=1
    fetch next from cursor_type into @name,@type


end
close cursor_type
DEALLOCATE cursor_type
exec (@sql)
end

另外对于数据库开发有兴趣的人,欢迎看一下我的一个博客
文章虽不多,但数据库里面的很多都是自己编写的,
http://hi.baidu.com/bb3852

 

默认分类 | 阅读 5171 次
文章评论,共0条
游客请输入验证码
浏览56565次