Skip to content

Instantly share code, notes, and snippets.

@oluies
Created February 20, 2017 14:07
Show Gist options
  • Save oluies/552483d751121a354973dff296d92b3d to your computer and use it in GitHub Desktop.
Save oluies/552483d751121a354973dff296d92b3d to your computer and use it in GitHub Desktop.
create spark StructFields from a SQL Server schema Raw
use [database_ONE_two]
select 'val ' + so.name + '_sch = StructType(Seq( ' + o.list + '))'
from sysobjects so
cross apply
(SELECT
' StructField("'+column_name+'", ' +
case data_type
when 'char' then 'StringType'
when 'varchar' then 'StringType'
when 'nvarchar' then 'StringType'
when 'bigint' then 'IntegerType'
when 'int' then 'IntegerType'
when 'bit' then 'BooleanType'
when 'datetime' then 'TimestampType'
when 'sql_variant' then ''
when 'text' then 'StringType'
when 'ntext' then 'StringType'
when 'xml' then 'StringType'
when 'decimal' then 'DataTypes.createDecimalType(' + cast(numeric_precision as varchar) + ', ' + cast(numeric_scale as varchar) + ')'
else coalesce('('+case when character_maximum_length = -1 then 'MAX' else cast(character_maximum_length as varchar) end +')','') end + ' ' +
', ' +
(case when IS_NULLABLE = 'No' then 'nullable = false ' else 'nullable = true' end ) +
+ '), '
from information_schema.columns where table_name = so.name
order by ordinal_position
FOR XML PATH('')) o (list)
left join
information_schema.table_constraints tc
on tc.Table_name = so.Name
AND tc.Constraint_Type = 'PRIMARY KEY'
cross apply
(select '[' + Column_Name + '], '
FROM information_schema.key_column_usage kcu
WHERE kcu.Constraint_Name = tc.Constraint_Name
ORDER BY
ORDINAL_POSITION
FOR XML PATH('')) j (list)
where xtype = 'U'
AND name NOT IN ('dtproperties')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment