sql 基于数据库表或视图创建类
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql 基于数据库表或视图创建类相关的知识,希望对你有一定的参考价值。
DECLARE @TableName varchar(2048) = 'PPB_DirectoryManager_TS_MailboxCacheExchange'
select * from information_schema.columns WHERE TABLE_NAME = @TableName
-- C# Classes
select
'public ' +
(CASE WHEN DATA_TYPE = 'bit' THEN 'bool'
WHEN DATA_TYPE = 'nvarchar' THEN 'string'
WHEN DATA_TYPE = 'varchar' THEN 'string'
WHEN DATA_TYPE = 'date' THEN 'DateTime'
WHEN DATA_TYPE = 'datetime' THEN 'DateTime'
WHEN DATA_TYPE = 'datetime2' THEN 'DateTime'
WHEN DATA_TYPE = 'uniqueidentifier' THEN 'Guid'
WHEN DATA_TYPE = 'int' THEN 'int'
WHEN DATA_TYPE = 'bigint' THEN 'long'
WHEN DATA_TYPE = 'smallint' THEN 'short'
WHEN DATA_TYPE = 'tinyint' THEN 'short'
WHEN DATA_TYPE = 'decimal' THEN 'decimal'
WHEN DATA_TYPE = 'numeric' THEN 'decimal'
WHEN DATA_TYPE = 'varbinary' THEN 'byte[]'
ELSE 'object' END) +
(CASE WHEN IS_NULLABLE = 'YES' AND DATA_TYPE NOT IN ('nvarchar', 'varchar') THEN '?' ELSE '' END) +
' ' + COLUMN_NAME + ' { get; set; }'
from information_schema.columns WHERE TABLE_NAME = @TableName
-- SQL Add
select
'@' + COLUMN_NAME + ' ' + DATA_TYPE +
CASE WHEN DATA_TYPE IN ('nvarchar', 'varchar', 'varbinary') THEN
CASE WHEN ISNULL(CHARACTER_MAXIMUM_LENGTH, -999) = -1 THEN '(MAX)'
WHEN ISNULL(CHARACTER_MAXIMUM_LENGTH, -999) >= 0 THEN '(' + CONVERT(varchar(max), CHARACTER_MAXIMUM_LENGTH) + ')'
ELSE '' END
WHEN DATA_TYPE IN ('datetime2', 'datetimeoffset') THEN
(CASE WHEN DATETIME_PRECISION IS NOT NULL THEN '(' + CONVERT(varchar(max), DATETIME_PRECISION) + ')' ELSE '' END)
WHEN DATA_TYPE IN ('decimal', 'numeric') THEN
(CASE WHEN NUMERIC_PRECISION IS NOT NULL THEN '(' + CONVERT(varchar(max), NUMERIC_PRECISION) + ', ' + CONVERT(varchar(max), NUMERIC_SCALE) +')' ELSE '' END)
ELSE '' END +
' = NULL,'
from information_schema.columns WHERE TABLE_NAME = @TableName
-- SQL Update
select
'[' + COLUMN_NAME + '] = @' + COLUMN_NAME + ','
from information_schema.columns WHERE TABLE_NAME = @TableName
以上是关于sql 基于数据库表或视图创建类的主要内容,如果未能解决你的问题,请参考以下文章
LINQ体验(18)——LINQ to SQL语句之视图和继承支持