阅读模式名,表名和列名从SQL数据库,并返回到C#代码 [英] Read Schema Name, Table Name and Column Name From a SQL DB and return to C# Code
问题描述
我有一个DB(在SQL Server 2008 SP3),并且需要所有模式名,表名和列名在C#代码相关的层次结构,我有SQLElement类别如下:
I have a DB (in SQL Server 2008 SP3) and need all Schema names, Table names and Column Names in related hierarchy in C# Code, I have the SQLElement Class as Following:
public class SQLElement
{
public string SchemaName { get; set; }
public string TableName { get; set; }
public string ColumnName { get; set; }
}
和有一个列表如下:
列表< SQLElement> SQLElementCollection =新的List< SQLElement>();
所以,我怎么能读的姓名从DB和将它们添加到这个列表(SQLElementCollection)
So how can I read Names from DB and add them to this List (SQLElementCollection)?
例如假设我们创建一个表是这样的:
for example assume we create a table like this:
Create Table [General].[City] (
[Id] BIGINT NOT NULL IDENTITY(1, 1),
[Title] NVARCHAR(30) NOT NULL DEFAULT (N''),
[Province_Id] BIGINT NOT NULL
)
和我需要名单如下:
[0]={SchemaName="General", TableName="City", ColumnName="Id"}
[1]={SchemaName="General", TableName="City", ColumnName="Title"}
[2]={SchemaName="General", TableName="City", ColumnName="Province_Id"}
任何一个是否对此有任何想法?
Does any one have any idea about this?
编辑:
在接下来的步骤中,我们怎么能得到每列的类型或相关的属性
In next step how we can get the type of each column or related properties?
推荐答案
我的建议是包括数据类型
> SQLElement 如果您有变更许可或创建另一个类的属性名称数据类型
,然后从 SQLElement $继承C $ C>,然后保存数据类型名称到它供以后使用,并使用下面的查询所有信息,谢谢
My suggestion is to include another member DataType
in SQLElement
if you have change permission or create another class with a property name DataType
and then inherit from SQLElement
and then save data type name into it for later use and use below query for all information, thanks
SELECT t.name AS TableName,
SCHEMA_NAME(t.schema_id) AS SchemaName,
c.name AS ColumnName,
tp.name as DataType
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
INNER JOIN sys.types tp ON c.system_type_id = tp.system_type_id
ORDER BY TableName;
这篇关于阅读模式名,表名和列名从SQL数据库,并返回到C#代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!