Skip to content

Instantly share code, notes, and snippets.

@csharpforevermore
Created May 20, 2021 10:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save csharpforevermore/0855f6f37874eae6c8914d55986de920 to your computer and use it in GitHub Desktop.
Save csharpforevermore/0855f6f37874eae6c8914d55986de920 to your computer and use it in GitHub Desktop.
Stored Procedure that generates a POCO from SQL
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Chris Randle
-- Create date: 17/02/2021
-- Description: Converts a SQL table into a basic CLR object (a "POCO" or "plain old CLR object")
-- =============================================
ALTER PROCEDURE [dbo].[TableToPoco]
-- Add the parameters for the stored procedure here
@schemaName NVARCHAR(MAX),
@tableName NVARCHAR(MAX),
@className NVARCHAR(MAX)
AS
BEGIN
SET NOCOUNT ON;
-- See https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql-server-data-type-mappings for any SQL types returning TODO with the ID of the type in brackets afterwards
DECLARE tableColumns CURSOR LOCAL FOR
SELECT cols.name, cols.system_type_id, cols.is_nullable FROM sys.columns cols
JOIN sys.tables tbl ON cols.object_id = tbl.object_id
WHERE tbl.name = @tableName
PRINT 'public class ' + @className
PRINT '{'
OPEN tableColumns
DECLARE @name NVARCHAR(MAX), @typeId INT, @isNullable BIT, @typeName NVARCHAR(MAX)
FETCH NEXT FROM tableColumns INTO @name, @typeId, @isNullable
WHILE @@FETCH_STATUS = 0
BEGIN
SET @typeName =
CASE @typeId
WHEN 36 THEN 'Guid' -- UniqueIdentifier
WHEN 48 THEN 'byte' -- TinyInt
WHEN 52 THEN 'short' -- SmallInt
WHEN 56 THEN 'int' -- Int
WHEN 61 THEN 'DateTime' -- DateTime
WHEN 104 THEN 'bool' -- Bit
WHEN 106 THEN 'decimal' -- Decimal(x, x)
WHEN 127 THEN 'long' -- BigInt
WHEN 231 THEN 'string' -- varchar
WHEN 239 THEN 'string' -- nvarchar
WHEN 241 THEN 'XElement'-- xml
ELSE 'TODO(' + CAST(@typeId AS NVARCHAR(100)) + ')'
END;
IF @isNullable = 1 AND @typeId != 231 AND @typeId != 239 AND @typeId != 241
SET @typeName = @typeName + '?'
PRINT ' public ' + @typeName + ' ' + @name + ' { get; set; }'
FETCH NEXT FROM tableColumns INTO @name, @typeId, @isNullable
END
PRINT '}'
CLOSE tableColumns
END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment