Saturday, December 04, 2010

How to Create Dynamically a Property Class from T-SQL

Some times we need to write huge classes with properties, its time consuming and boring . Here is a work around how you can do this from T-SQL.

use master
go
Declare @tableName varchar(50)
SET @tableName = 'bangaram'
SELECT case when sc.isnullable<>0 AND st.name NOT LIKE 'varchar' AND st.name NOT LIKE 'text' then  
'private System.Nullable<'+REPLACE(REPLACE(REPLACE(REPLACE(st.name,'varchar','string'),'bit','bool'),'datetime','DateTime'),'text','string')+ '> _'  +sc.name +';
 public System.Nullable<'+REPLACE(REPLACE(REPLACE(REPLACE(st.name,'varchar','string'),'bit','bool'),'datetime','DateTime'),'text','string')+ '> '+sc.name
else 
'private '+REPLACE(REPLACE(REPLACE(REPLACE(st.name,'varchar','string'),'bit','bool'),'datetime','DateTime'),'text','string')+ ' _'  +sc.name +';
 public '+REPLACE(REPLACE(REPLACE(REPLACE(st.name,'varchar','string'),'bit','bool'),'datetime','DateTime'),'text','string')+ ' '+sc.name  
  end ,
        '{
            get { return this._'+sc.name+'; }
            set { if ((this._'+sc.name+' != value)) { this._'+sc.name+' = value; } }
        }'
FROM Syscolumns sc INNER JOIN Systypes st on st.xtype=sc.xtype
WHERE sc.id in(SELECT id FROm sysobjects WHERE name=@tableName)
ORDER BY sc.id

Replace @tablename with your table name in your database table. One more thing I have give @tablename size as varchar(50) increase if your tablename is bigger. That’s all you need to do apart from little bit of formatting..Good luck guys. Have fun..Smile

No comments:

Post a Comment