我想查询一个表的所有列的名称。我发现如何做到这一点:

甲骨文 MySQL PostgreSQL

但我也需要知道:如何在Microsoft SQL Server(在我的情况下是2008年)中做到这一点?


当前回答

这个SO问题缺少以下方法:

-- List down all columns of table 'Logging'
select * from sys.all_columns where object_id = OBJECT_ID('Logging')

其他回答

--This is another variation used to document a large database for conversion (Edited to --remove static columns)

SELECT o.Name                   as Table_Name
     , c.Name                   as Field_Name
     , t.Name                   as Data_Type
     , t.length                 as Length_Size
     , t.prec                   as Precision_
FROM syscolumns c 
     INNER JOIN sysobjects o ON o.id = c.id
     LEFT JOIN  systypes t on t.xtype = c.xtype  
WHERE o.type = 'U' 
ORDER BY o.Name, c.Name

--In the left join, c.type is replaced by c.xtype to get varchar types

另一个更直观的选择是:

SELECT [name] 
FROM sys.columns 
WHERE object_id = OBJECT_ID('[yourSchemaType].[yourTableName]') 

这将在一个列中提供所有列名。 如果您关心其他元数据,可以将SELECT语句编辑为SELECT *。

SQL生成SQL:

DROP TABLE IF EXISTS test;
CREATE TABLE test (
  col001 INTEGER
, col002 INTEGER
, col003 INTEGER
, col004 INTEGER
, col005 INTEGER
, col006 INTEGER
, col007 INTEGER
, col008 INTEGER
, col009 INTEGER
, col010 INTEGER
)
;
INSERT INTO test(col001) VALUES(1);
INSERT INTO test(col002) VALUES(1);
INSERT INTO test(col005) VALUES(1);
INSERT INTO test(col009) VALUES(1);
INSERT INTO test VALUES (NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);

SELECT
  CASE ROW_NUMBER() OVER(ORDER BY ordinal_position)
  WHEN 1 THEN 
    'SELECT'+CHAR(10)+'  *'+CHAR(10)+'FROM test'
   +CHAR(10)+'WHERE '
  ELSE
    '   OR '
  END
+ column_name +' IS NOT NULL'
+ CASE ROW_NUMBER() OVER(ORDER BY ordinal_position DESC)
  WHEN 1 THEN 
    CHAR(10)+';'
  ELSE
    ''
  END
  FROM information_schema.columns
  WHERE table_schema='dbo'
    AND table_name = 'test'
ORDER BY
  ordinal_position;

-- the whole scenario. Works for 10 , will work for 100, too:

-- out -----------------------------------------------
-- out  SELECT
-- out   *
-- out FROM test
-- out WHERE col001 IS NOT NULL
-- out     OR col002 IS NOT NULL
-- out     OR col003 IS NOT NULL
-- out     OR col004 IS NOT NULL
-- out     OR col005 IS NOT NULL
-- out     OR col006 IS NOT NULL
-- out     OR col007 IS NOT NULL
-- out     OR col008 IS NOT NULL
-- out     OR col009 IS NOT NULL
-- out     OR col010 IS NOT NULL
-- out ;

通过使用这个查询,您可以得到答案:

select Column_name 
from Information_schema.columns 
where Table_name like 'table name'

您可以编写此查询来获得列名和所有详细信息,而无需使用 MySql中的INFORMATION_SCHEMA:

SHOW COLUMNS FROM database_Name.table_name;