本文推出SqlServer表转化为实体的sql代码
在VS中有可以自带生成实体类的快捷操作,但是生成的代码比较杂乱,很多东西都是不需要的,一个一个去敲又很浪费时间,关键太无聊了
在闲暇之余写一份代码供大家学习,废话不多说,直接整干货:
1 DECLARE @TableName sysname = 'ObjeckBLL';-- 要生成实体类的表名 2 DECLARE @Result VARCHAR(MAX) = 'public class ' + @TableName + ' 3 {'; 4 SELECT @Result = @Result + ' 5 /// <summary> 6 /// ' + CAST(t.Summary AS VARCHAR(MAX)) + ' 7 /// </summary> 8 public ' + ColumnType + NullableSign + ' ' + ColumnName + ' { get; set; } 9 ' 10 FROM 11 ( 12 SELECT REPLACE(col.name, ' ', '_') ColumnName, 13 col.column_id ColumnId, 14 CASE typ.name 15 WHEN 'bigint' THEN 16 'long' 17 WHEN 'binary' THEN 18 'byte[]' 19 WHEN 'bit' THEN 20 'bool' 21 WHEN 'char' THEN 22 'string' 23 WHEN 'date' THEN 24 'DateTime' 25 WHEN 'datetime' THEN 26 'DateTime' 27 WHEN 'datetime2' THEN 28 'DateTime' 29 WHEN 'datetimeoffset' THEN 30 'DateTimeOffset' 31 WHEN 'decimal' THEN 32 'decimal' 33 WHEN 'float' THEN 34 'float' 35 WHEN 'image' THEN 36 'byte[]' 37 WHEN 'int' THEN 38 'int' 39 WHEN 'money' THEN 40 'decimal' 41 WHEN 'nchar' THEN 42 'char' 43 WHEN 'ntext' THEN 44 'string' 45 WHEN 'numeric' THEN 46 'decimal' 47 WHEN 'nvarchar' THEN 48 'string' 49 WHEN 'real' THEN 50 'double' 51 WHEN 'smalldatetime' THEN 52 'DateTime' 53 WHEN 'smallint' THEN 54 'short' 55 WHEN 'smallmoney' THEN 56 'decimal' 57 WHEN 'text' THEN 58 'string' 59 WHEN 'time' THEN 60 'TimeSpan' 61 WHEN 'timestamp' THEN 62 'DateTime' 63 WHEN 'tinyint' THEN 64 'byte' 65 WHEN 'uniqueidentifier' THEN 66 'Guid' 67 WHEN 'varbinary' THEN 68 'byte[]' 69 WHEN 'varchar' THEN 70 'string' 71 ELSE 72 'UNKNOWN_' + typ.name 73 END ColumnType, 74 CASE 75 WHEN col.is_nullable = 1 76 AND typ.name IN ( 'bigint', 'bit', 'date', 'datetime', 'datetime2', 'datetimeoffset', 'decimal', 77 'float', 'int', 'money', 'numeric', 'real', 'smalldatetime', 'smallint', 78 'smallmoney', 'time', 'tinyint', 'uniqueidentifier' 79 ) THEN 80 '?' 81 ELSE 82 '' 83 END NullableSign, 84 ISNULL(ep.value, col.name) AS Summary 85 FROM sys.columns col 86 JOIN sys.types typ 87 ON col.system_type_id = typ.system_type_id 88 AND col.user_type_id = typ.user_type_id 89 LEFT JOIN sys.extended_properties ep 90 ON ep.major_id = col.object_id 91 AND ep.minor_id = col.column_id 92 WHERE col.object_id = OBJECT_ID(@TableName) 93 ) t 94 ORDER BY ColumnId; 95 SET @Result = @Result + ' 96 }'; 97 PRINT @Result;View Code
来看看效果:
有没有瞬间觉得很爽,排版清晰,结构清楚
今天的分享到此结束,有需要的可以关注留言讨论
能帮朋友解决问题的记得给个关注支持一下,以后将多多分享SQL SERVER 相关知识