假设我在SQLServer中有一个名为MyTable的表
ID FirstName LastName
1 Harry Dan
2 Maria Vicente
3 Joe Martin
现在,如果我必须在表格中插入任何数据,我将简单地像这样触发插入查询
INSERT INTO MyTable (ID, FirstName, LastName) VALUES (4, Smith, Dan);
但是,如果我事先不知道列名,我只知道表名。那么有没有办法在运行时获取表的列名?
答案 0 :(得分:9)
您可以使用sql -
SELECT name FROM sys.columns WHERE object_id = OBJECT_ID('TABLE_NAME')
答案 1 :(得分:4)
或者您可以查询SELECT TOP 0 * FROM TableName
。然后,您可以获得列:
using(var reader = command.ExecuteReader())
{
reader.Read();
var table = reader.GetSchemaTable();
foreach (DataColumn column in table.Columns)
{
Console.WriteLine(column.ColumnName);
}
}
答案 2 :(得分:3)
使用纯C#/ .NET代码的另一个选项: 首先是一个辅助方法,它返回一个简单的列名列表。使用DataTable保存表架构信息意味着还可以为每列(fx)检索其他信息。如果它是AutoIncreament专栏等。
private IEnumerable<string> GetColumnNames(string conStr, string tableName)
{
var result = new List<string>();
using (var sqlCon = new SqlConnection(conStr))
{
sqlCon.Open();
var sqlCmd = sqlCon.CreateCommand();
sqlCmd.CommandText = "select * from " + tableName + " where 1=0"; // No data wanted, only schema
sqlCmd.CommandType = CommandType.Text;
var sqlDR = sqlCmd.ExecuteReader();
var dataTable = sqlDR.GetSchemaTable();
foreach (DataRow row in dataTable.Rows) result.Add(row.Field<string>("ColumnName"));
}
return result;
}
该方法可以称为:
var sortedNames = GetColumnNames("Data Source=localhost;Initial Catalog=OF2E;Integrated Security=SSPI", "Articles").OrderBy(x => x);
foreach (var columnName in sortedNames) Console.WriteLine(columnName);
答案 3 :(得分:1)
只需通过此查询:
SELECT * FROM sys.columns
WHERE object_id = OBJECT_ID('dbo.[table_name]')
或者此查询:
SELECT COLUMN_NAME
FROM information_schema.columns
WHERE TABLE_NAME = [table_name]
ORDER BY COLUMN_NAME
答案 4 :(得分:0)
此问题之前已在各种主题中得到解答
检查:
How can I get column names from a table in SQL Server?
答案 5 :(得分:0)
var ColName = "";
var model = new AttributeMappingSource().GetModel(typeof(DataClassesDataContext));
foreach (var mt in model.GetTables())
{
if (mt.TableName == "dbo.Table_Name")
{
foreach (var dm in mt.RowType.DataMembers)
{
ColName = dm.MappedName + ", ";
Response.Write(ColName);
}
}
}