本文推出SqlServer表转化为实体的sql代码
在VS中有可以自带生成实体类的快捷操作,但是生成的代码比较杂乱,很多东西都是不需要的,一个一个去敲又很浪费时间,关键太无聊了
在闲暇之余写一份代码供大家学习,废话不多说,直接整干货:
DECLARE @TableName sysname = '[dbo].[Orders]';-- 要生成实体类的表名 DECLARE @Result VARCHAR(MAX) = 'public class ' + @TableName + ' {'; SELECT @Result = @Result + ' /// <summary> /// ' + CAST(t.Summary AS VARCHAR(MAX)) + ' /// </summary> public ' + ColumnType + NullableSign + ' ' + ColumnName + ' { get; set; } ' FROM ( SELECT REPLACE(col.name, ' ', '_') ColumnName, col.column_id ColumnId, CASE typ.name WHEN 'bigint' THEN 'long' WHEN 'binary' THEN 'byte[]' WHEN 'bit' THEN 'bool' WHEN 'char' THEN 'string' WHEN 'date' THEN 'DateTime' WHEN 'datetime' THEN 'DateTime' WHEN 'datetime2' THEN 'DateTime' WHEN 'datetimeoffset' THEN 'DateTimeOffset' WHEN 'decimal' THEN 'decimal' WHEN 'float' THEN 'float' WHEN 'image' THEN 'byte[]' WHEN 'int' THEN 'int' WHEN 'money' THEN 'decimal' WHEN 'nchar' THEN 'char' WHEN 'ntext' THEN 'string' WHEN 'numeric' THEN 'decimal' WHEN 'nvarchar' THEN 'string' WHEN 'real' THEN 'double' WHEN 'smalldatetime' THEN 'DateTime' WHEN 'smallint' THEN 'short' WHEN 'smallmoney' THEN 'decimal' WHEN 'text' THEN 'string' WHEN 'time' THEN 'TimeSpan' WHEN 'timestamp' THEN 'DateTime' WHEN 'tinyint' THEN 'byte' WHEN 'uniqueidentifier' THEN 'Guid' WHEN 'varbinary' THEN 'byte[]' WHEN 'varchar' THEN 'string' ELSE 'UNKNOWN_' + typ.name END ColumnType, CASE WHEN col.is_nullable = 1 AND typ.name IN ( 'bigint', 'bit', 'date', 'datetime', 'datetime2', 'datetimeoffset', 'decimal', 'float', 'int', 'money', 'numeric', 'real', 'smalldatetime', 'smallint', 'smallmoney', 'time', 'tinyint', 'uniqueidentifier' ) THEN '?' ELSE '' END NullableSign, ISNULL(ep.value, col.name) AS Summary FROM sys.columns col JOIN sys.types typ ON col.system_type_id = typ.system_type_id AND col.user_type_id = typ.user_type_id LEFT JOIN sys.extended_properties ep ON ep.major_id = col.object_id AND ep.minor_id = col.column_id WHERE col.object_id = OBJECT_ID(@TableName) ) t ORDER BY ColumnId; SET @Result = @Result + ' }'; PRINT @Result;
来看看效果:
有没有瞬间觉得很爽,排版清晰,结构清楚
今天的分享到此结束,有需要的可以关注留言讨论
能帮朋友解决问题的记得给个关注支持一下,以后将多多分享SQL SERVER 相关知识
标签:ERVER,C#,decimal,WHEN,col,Result,SQL,typ,id From: https://www.cnblogs.com/51net/p/17417886.html