如何在sql中获取列名 [英] how to get a column name in sql

查看:220
本文介绍了如何在sql中获取列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请有人告诉我如何使用c#从sql表中检索单个列名。请尽快回复 。请提供代码。

解决方案

您可以使用简单的SQL语句检索表的所有列:

  SELECT  column_name  FROM  information_schema.columns  WHERE  table_name = ' 我的表名' 


你可以这样试试

 SqlConnection con = con =  new  SqlConnection(< span class =code-comment> //  此处的连接字符串 
);
SqlCommand cmd = new SqlCommand(选择* 来自 [我的表名],con);
SqlDataReader sdr = cmd.ExecuteReader();

string columnName = sdr.GetName( 0 );



在这里,您将获得第一列名称到columnName变量,通过更改索引,您将获得表中存在的不同列名。

我希望它能帮到你。


从表中获取列名并将其分配给标签(VB.NET)。 

Dim c As New SqlConnection(< connection string >
c.open ()
Dim命令As SqlCommand = c.CreateCommand()
command.CommandText =SELECT name FROM sys.columns WHERE object_id = OBJECT_ID('< 名称 > ')和column_id ='< id > '
Dim reader As SqlDataReader = command.ExecuteReader()
reader.Read()
Label1.text = reader.Item(0).ToString
c.close()


Please Anyone tell me how to retrieve a single column name from sql table using c#. please Reply as quick as possible. please provide the code too.

解决方案

You can retrieve all the columns for a table with a simple SQL statement:

SELECT column_name FROM information_schema.columns WHERE table_name = 'My Table Name'


You can Try like this

SqlConnection con=con = new SqlConnection(//your connection string here
);
SqlCommand cmd = new SqlCommand(Select * from [My Table Name], con);
                      SqlDataReader  sdr = cmd.ExecuteReader();

                  string  columnName = sdr.GetName(0);


Here you will get your first column name in to the "columnName" variable, by changing the index you will get different column names which are present in your table.
I hope it will helps you.


Fetch the column name from table and assign it to the label(VB.NET).

Dim c As New SqlConnection("<connection string>")
c.open()
Dim command As SqlCommand = c.CreateCommand()
command.CommandText ="SELECT name FROM sys.columns WHERE object_id = OBJECT_ID('<column name>') and column_id='<column id>' "
Dim reader As SqlDataReader = command.ExecuteReader()
reader.Read()
Label1.text = reader.Item(0).ToString
c.close()


这篇关于如何在sql中获取列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆