-
Nov 5th, 2021, 10:48 AM
#1
[SQL Server] Generate Angular Interfaces from Table Schema
I got very tired of manually writing my Angular modals, so I whipped up a quick code generator to do it for me.
To use it, start a new query, change the value of the @TableName variable, and hit run.
A couple of notes, this will create an interface, it does not respect nullable (i.e. it makes every property nullable), and if it runs across a SQL type that it cannot map then it defaults it to string.
Code:
SET NOCOUNT ON;
DECLARE @TableName VARCHAR(64); SET @TableName = '--change me--';
DECLARE @TempTable TABLE (Id VARCHAR(64) NOT NULL, ColumnName VARCHAR(64) NOT NULL, DataType VARCHAR(64) NOT NULL);
DECLARE @DataTable TABLE (Id VARCHAR(64) NOT NULL, SqlDataType VARCHAR(64) NOT NULL, AngularDataType VARCHAR(64) NOT NULL);
INSERT INTO @DataTable VALUES
(NEWID(), 'bigint', 'number'),
(NEWID(), 'decimal', 'number'),
(NEWID(), 'int', 'number'),
(NEWID(), 'money', 'number'),
(NEWID(), 'numeric', 'number'),
(NEWID(), 'smalllint', 'number'),
(NEWID(), 'smallmoney', 'number'),
(NEWID(), 'tinyint', 'number'),
(NEWID(), 'float', 'number'),
(NEWID(), 'real', 'number'),
(NEWID(), 'date', 'Date'),
(NEWID(), 'datetime2', 'Date'),
(NEWID(), 'datetime', 'Date'),
(NEWID(), 'datetimeoffset', 'Date'),
(NEWID(), 'smalldatetime', 'Date'),
(NEWID(), 'time', 'Date'),
(NEWID(), 'char', 'string'),
(NEWID(), 'varchar', 'string'),
(NEWID(), 'text', 'string'),
(NEWID(), 'nchar', 'string'),
(NEWID(), 'nvarchar', 'string'),
(NEWID(), 'ntext', 'string'),
(NEWID(), 'binary', 'string'),
(NEWID(), 'varbinary', 'string'),
(NEWID(), 'image', 'string');
INSERT INTO @TempTable SELECT
NEWID() AS Id,
ColumnInformation.COLUMN_NAME AS ColumnName,
ColumnInformation.DATA_TYPE AS DataType
FROM
INFORMATION_SCHEMA.COLUMNS AS ColumnInformation
WHERE
ColumnInformation.TABLE_NAME = @TableName;
PRINT 'export interface I' + @TableName + ' {';
WHILE EXISTS(SELECT * FROM @TempTable)
BEGIN
-- get the topmost record
DECLARE @TempId VARCHAR(64);
DECLARE @ColumnName VARCHAR(64);
DECLARE @SqlType VARCHAR(64);
DECLARE @AngularType VARCHAR(64);
SELECT TOP 1 @TempId = Id, @ColumnName = ColumnName, @SqlType = DataType FROM @TempTable;
SELECT TOP 1 @AngularType = COALESCE(AngularDataType, 'string') FROM @DataTable WHERE SqlDataType = @SqlType;
PRINT ' ' + @ColumnName + '?: ' + @AngularType + ';';
-- delete the topmost record
DELETE FROM @TempTable WHERE Id = @TempId;
END;
PRINT '}';
SET NOCOUNT OFF;
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|