How can I get column names from a table in SQL Server?

前端 未结 20 1576
既然无缘
既然无缘 2020-11-22 09:29

I want to query the name of all columns of a table. I found how to do this in:

  • Oracle
  • MySQL
  • PostgreSQL

But I also need to know:

20条回答
  •  执笔经年
    2020-11-22 10:21

    Some SQL Generating 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 ;
    
    

提交回复
热议问题