Friday, June 27, 2008

Generate Create Script from existing table in Foxpro

Generate Create Script from existing table in Foxpro

Following code generates sql create table script for table or cursor in current workspace.



FUNCTION GenerateCreateScript
LPARAMETERS tcCursor
LOCAL ARRAY aa[1]
LOCAL lcAlias, lcCursor, lnFields, lcsql, lcfield, lcType, lnlen, lnDecimal, lnI
lcAlias = ALIAS()
IF EMPTY(lcAlias)
RETURN ''
ENDIF

IF EMPTY(tcCursor) OR VARTYPE(tcCursor) # 'C'
lcCursor = SYS(2015)
ELSE
lcCursor = tcCursor
ENDIF
lnFields = AFIELDS(aa)

lcsql = [ create cursor ] + lcCursor + [ (]
FOR lnI = 1 TO lnFields
lcfield = aa[lni, 1]
lcType = aa[lni, 2]
lnlen = aa[lni, 3]
lnDecimal = aa[lni, 4]
lcsql = lcsql + lcfield + ' ' + lcType + [(] + TRANSFORM(lnlen)
IF lnDecimal > 0
lcsql = lcsql + [,] + TRANSFORM(lnDecimal)
ENDIF
lcsql = lcsql + [)]
IF lnI = lnFields
lcsql = lcsql +[ ;] + CHR(13) + CHR(10) + [)]
ELSE
lcsql = lcsql + [ ;] + CHR(13) + CHR(10) + [, ]
ENDIF
ENDFOR

RETURN lcsql
ENDFUNC

No comments: