Home Forums Programming General TSQL snippet: table to .Net class generator RE: TSQL snippet: table to .Net class generator

  • Here is a vesion without any Cursors:

    create proc spVB_Make_Class as

    --from Lambert Antonio, 26-jun-2008

    Set NoCount ON

    declare @field table (id int identity primary key clustered, fieldname varchar(50), fieldtype varchar(50))

    declare @table_name varchar(50)

    set @table_name = 'TargetTable' -- this is the table name

    insert into @field

    Select sc.name

    , case st.name

    when 'int' then 'Int32'

    when 'tinyint' then 'Int32'

    when 'varchar' then 'String'

    when 'bit' then 'Boolean'

    when 'float' then 'Double'

    when 'datetime' then 'Datetime'

    else st.name

    end As [name]

    from

    sysobjects so,

    syscolumns sc,

    systypes st

    where

    so.id = sc.id

    and so.xtype = 'U'

    and so.name = @table_name

    and st.xtype = sc.xtype

    declare @VB table (id int identity primary key clustered, Line varchar(8000))

    declare @constructor table (id int identity(1000000,1) primary key clustered, Line varchar(8000))

    declare @assign table (id int identity(1000000,1) primary key clustered, Line varchar(8000))

    Insert into @VB(Line) Select 'Public Class ' + @table_name

    Insert into @VB(Line)

    Select '

    Private _' + fieldname + ' AS ' + fieldtype + '

    Public Property ' + fieldname + '() AS ' + fieldtype + '

    Get

    return _' + fieldname + '

    End Get

    Set (value AS ' + fieldtype + ')

    _' + fieldname + ' = value

    End Set

    End Property

    '

    From @field

    Order By ID

    Insert into @constructor(Line)

    Select 'ByVal v' + fieldname + ' AS ' + fieldtype + ', '

    From @field

    Order By ID

    Insert into @assign(Line)

    Select '_' + fieldname + ' = v' + fieldname

    From @field

    Order By ID

    Insert into @VB(Line) Select 'Public Sub New('

    Insert into @VB(Line) Select '' + Line From @constructor Order By ID

    Insert into @VB(Line) Select ')'

    Insert into @VB(Line) Select '' + Line From @assign Order By ID

    Insert into @VB(Line) Select '

    End Sub

    End Class'

    Select Line From @VB Order By ID

    [font="Times New Roman"]-- RBarryYoung[/font], [font="Times New Roman"] (302)375-0451[/font] blog: MovingSQL.com, Twitter: @RBarryYoung[font="Arial Black"]
    Proactive Performance Solutions, Inc.
    [/font]
    [font="Verdana"] "Performance is our middle name."[/font]