SQL 按字母顺序列出所有列名

发布于 2024-09-30 02:10:24 字数 230 浏览 4 评论 0原文

我知道这

SELECT * FROM Table

将列出表中的所有列,但我有兴趣按字母顺序列出列。

假设我有三列,“姓名”、“年龄”和“性别”。

我想要以以下格式组织列

|age| |name| |sex|

Is it possible to do this with SQL?

I know that

SELECT * FROM Table

will list all columns in the table, but I am interested in listing the columns in alphabetical order.

Say, I have three columns, "name", "age" and "sex".

I want the columns organized in the format

|age| |name| |sex|

Is it possible to do this with SQL?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

蹲在坟头点根烟 2024-10-07 02:10:24

这会生成一个查询,其中所有列在 select 语句中按字母顺序排列。

DECLARE @QUERY VARCHAR(2000)
DECLARE @TABLENAME VARCHAR(50) = '<YOU_TABLE>'

SET @QUERY = 'SELECT '
SELECT @QUERY = @QUERY + Column_name + ', 
'
  FROM INFORMATION_SCHEMA.COLUMNS 
 WHERE TABLE_NAME = @TABLENAME
 ORDER BY Column_name

SET @QUERY =  LEFT(@QUERY, LEN(@QUERY) - 4) + ' 
FROM '+ @TABLENAME

PRINT @QUERY
EXEC(@QUERY)

This generates a query with all columns ordered alphabetically in the select statement.

DECLARE @QUERY VARCHAR(2000)
DECLARE @TABLENAME VARCHAR(50) = '<YOU_TABLE>'

SET @QUERY = 'SELECT '
SELECT @QUERY = @QUERY + Column_name + ', 
'
  FROM INFORMATION_SCHEMA.COLUMNS 
 WHERE TABLE_NAME = @TABLENAME
 ORDER BY Column_name

SET @QUERY =  LEFT(@QUERY, LEN(@QUERY) - 4) + ' 
FROM '+ @TABLENAME

PRINT @QUERY
EXEC(@QUERY)
坏尐絯℡ 2024-10-07 02:10:24

是的,也不是:-)

SQL 本身并不关心列以什么顺序出现,但是,如果您要使用:

select age, name, sex from ...

您会发现它们可能按该顺序出现(尽管我不确定 SQL 标准是否强制要求)这)。

现在您可能不想这样做,但有时生活并不公平:-)

您还可以使用 DBMS 数据定义表来动态构建查询。这是不可移植的,但大多数 DBMS 都提供这些表(例如 DB/2 的 SYSIBM.SYSCOLUMNS ),您可以从其中以有序的方式选择列名称。类似于:

select column_name from sysibm.syscolumns
where owner = 'pax' and table_name = 'movies'
order by column_name;

然后您使用那个查询的结果来构建真正的查询:

query1 = "select column_name from sysibm.syscolumns" +
         " where owner = 'pax' and table_name = 'movies'" +
         " order by column_name"
rs = exec(query1)
query2 = "select"
sep = " "
foreach colm in rs:
    query2 += sep + colm["column_name"]
    sep = ", "
query2 += " from movies order by rating"
rs = exec(query2)
// Now you have the rs recordset with sorted columns.

但是,您确实应该严格检查选择*的所有查询 - 在绝大多数情况下,这是不必要的且低效的。数据的表示可能应该由表示层而不是 DBMS 本身来完成 - DBMS 应该以尽可能高效的方式返回数据。

Yes, and no :-)

SQL itself doesn't care what order the columns come out in but, if you were to use:

select age, name, sex from ...

you'd find that they probably came out in that order (though I'm not sure SQL standards mandate this).

Now you may not want to do that but sometimes life isn't fair :-)

You also have the other possibility of using the DBMS data definition tables to dynamically construct a query. This is non-portable but most DBMS' supply these table (such as DB/2's SYSIBM.SYSCOLUMNS) and you can select the column names from there in an ordered fashion. Something like:

select column_name from sysibm.syscolumns
where owner = 'pax' and table_name = 'movies'
order by column_name;

Then you use the results of that query to construct the real query:

query1 = "select column_name from sysibm.syscolumns" +
         " where owner = 'pax' and table_name = 'movies'" +
         " order by column_name"
rs = exec(query1)
query2 = "select"
sep = " "
foreach colm in rs:
    query2 += sep + colm["column_name"]
    sep = ", "
query2 += " from movies order by rating"
rs = exec(query2)
// Now you have the rs recordset with sorted columns.

However, you really should critically examine all queries that select * - in the vast majority of cases, it's unnecessary and inefficient. And presentation of the data is something that should probably be done by the presentation layer, not the DBMS itself - the DBMS should be left to return the data in as efficient a manner as possible.

oО清风挽发oО 2024-10-07 02:10:24
  • 如果没有动态 SQL,就无法自动执行此操作。
  • 不建议使用 SELECT *,并且不会对列名进行排序。
  • 您必须显式执行 SELECTage, name, sex FROM

在 SQL 级别,这并不重要。这对于任何客户端代码对象都不重要 -

如果它很重要,那么在向客户端呈现数据时进行排序。

抱歉,事情就是这样……

  • There is no way to do this automatically without dynamic SQL.
  • SELECT * is not recommended and will not sort column names
  • You'd have to explicitly do SELECT age, name, sex FROM

At the SQL level, it does not matter. Not does it matter to any client code object-

If it's important, then sort when you present the data to the client.

Sorry, it just is that way...

才能让你更想念 2024-10-07 02:10:24

SQL-92 标准指定,当使用SELECT * 时,按列在表中的序号位置的升序引用列。相关部分为 4.8(列)和 7.9(查询规范)。我不知道有任何供应商对标准的扩展允许以任何其他顺序返回列,可能是因为通常不鼓励使用 SELECT * 。

您可以使用 SQL DDL 来确保列的顺序位置与所需的字母顺序相匹配。但是,只有在 FROM 子句中引用 sinlge 表时,这才会按照您想要的方式工作。如果引用两个表,SELECT * 将按序号位置顺序返回第一个表中的列,然后按序号位置返回第二个表的列,因此完整结果集的列可能不按字母顺序排列。

SQL-92 Standard specifies that when using SELECT * the columns are referenced in the ascending sequence of their ordinal position within the table. The relevant sections are 4.8 (columns) and 7.9 (query specification). I don't know of any vendor extensions to the Standard that would allow columns to be returned in any other order, probably because use of SELECT * is generally discouraged.

You can use SQL DDL to ensure that columns' ordinal positions match the desired alphabetical order. However, this will only work in the way you want when referening a sinlge table in the FROM clause. If two tables are referenced, SELECT * will return the columns from the first table in ordinal position order followed by the second table's columns in ordinal position, so the complete resultset's columns may not be in alphabetical order.

江南月 2024-10-07 02:10:24

如果您只是想在 SQL Server 上查找列。

SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'MyTableThatCouldMaybeNeedNormalising'
order by COLUMN_NAME

If you just trying to find a column, on SQL Server.

SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'MyTableThatCouldMaybeNeedNormalising'
order by COLUMN_NAME
薄荷港 2024-10-07 02:10:24

您可以只指定要选择的列:

SELECT age, name, sex FROM Table

列将按照您在查询中指定的顺序显示。

You may just specify columns you wish to select:

SELECT age, name, sex FROM Table

Columns will be shown in the same order as you specified them in query.

为你拒绝所有暧昧 2024-10-07 02:10:24

另一种方法是通过 SQL 过程更改表来按字母顺序排列所有列。我为几个表创建了一个表,在这些表中,我的用户更喜欢字母布局,同时仍然使用简化的 SELECT * 语句。

这段代码应该首先安排我的索引,然后组织 AZ 中的所有其他列。对于您的实例来说,它可能有所不同,但这是一个很好的起点。

DELIMITER ;;

DROP PROCEDURE IF EXISTS ALPHABETISE_TABLE_COLUMNS;

CREATE PROCEDURE ALPHABETISE_TABLE_COLUMNS(IN database_name VARCHAR(64), IN table_name_string VARCHAR(64), IN index_name_string VARCHAR(64))

BEGIN

    DECLARE n INT DEFAULT 0;
    DECLARE i INT DEFAULT 0;
    DECLARE col_name VARCHAR(30) DEFAULT "";
    DECLARE col_datatype VARCHAR(10) DEFAULT "";
    DECLARE previous_col VARCHAR(30) DEFAULT col_name;

    SELECT COUNT(*) 
    FROM 
        (SELECT COLUMN_NAME 
        FROM INFORMATION_SCHEMA.COLUMNS 
        WHERE TABLE_NAME = table_name_string) AS TEMP 
    INTO n;

    SET @Q= CONCAT('ALTER TABLE `',database_name,'`.`',table_name_string,'` CHANGE COLUMN `',index_name_string,'` `',index_name_string,'` BIGINT(20) NOT NULL FIRST');
    PREPARE exe FROM @Q;
    EXECUTE exe;
    DEALLOCATE PREPARE exe;

    SET n = n-1;
    SET i=1;

    WHILE i<n DO 


        SELECT COLUMN_NAME FROM 
            (SELECT COLUMN_NAME, @row_num:= @row_num + 1 as ind_rows 
            FROM INFORMATION_SCHEMA.COLUMNS, (SELECT @row_num:= 0 AS num) AS c 
            WHERE TABLE_NAME = table_name_string AND COLUMN_NAME <> index_name_string 
            ORDER BY COLUMN_NAME ASC) as TEMP 
        WHERE ind_rows = i 
        INTO col_name;

        SELECT DATA_TYPE 
        FROM 
            (SELECT DATA_TYPE, @row_num:= @row_num + 1 as ind_rows 
            FROM INFORMATION_SCHEMA.COLUMNS, (SELECT @row_num:= 0 AS num) AS c 
            WHERE TABLE_NAME = table_name_string AND COLUMN_NAME <> index_name_string 
            ORDER BY COLUMN_NAME ASC) as TEMP 
        WHERE ind_rows = i 
        INTO col_datatype;

        IF i = 1 THEN
            SET previous_col = index_name_string;
        ELSE
            SELECT COLUMN_NAME 
            FROM 
                (SELECT COLUMN_NAME, @row_num:= @row_num + 1 as ind_rows 
                FROM INFORMATION_SCHEMA.COLUMNS, (SELECT @row_num:= 0 AS num) AS c 
                WHERE TABLE_NAME = table_name_string AND COLUMN_NAME <> index_name_string 
                ORDER BY COLUMN_NAME ASC) as TEMP 
            WHERE ind_rows = i-1
            INTO previous_col;
        END IF;

        IF col_datatype = 'varchar' THEN
            SET col_datatype = 'TEXT';
        END IF;

        select col_name, previous_col;
        IF col_name <> index_name_string OR index_name_string = '' THEN
            SET @Q= CONCAT('ALTER TABLE `',database_name,'`.`',table_name_string,'` CHANGE COLUMN `',col_name,'` `',col_name,'` ',col_datatype,' NULL DEFAULT NULL AFTER `',previous_col,'`');
            PREPARE exe FROM @Q;
            EXECUTE exe;
            DEALLOCATE PREPARE exe;
        END IF;
        SET i = i + 1;

    END WHILE;
END;
;;

DELIMITER ;

# NOTE: ASSUMES INDEX IS BIGINT(20), IF OTHER PLEASE ADAPT IN LINE 22 TO MEET DATATYPE
#
# CALL ALPHABETISE_TABLE_COLUMNS('database_name', 'column_name', 'index_name')

希望这有帮助!

A different approach would be to arrange all columns alphabetically by altering the table via a SQL procedure. I created one for a couple of the tables in which my users prefer the alphabetic layout while still using the simplified SELECT * statement.

This code should arranged my index first and then organise all other columns from A-Z. It may be different for your instance but is a good starting point.

DELIMITER ;;

DROP PROCEDURE IF EXISTS ALPHABETISE_TABLE_COLUMNS;

CREATE PROCEDURE ALPHABETISE_TABLE_COLUMNS(IN database_name VARCHAR(64), IN table_name_string VARCHAR(64), IN index_name_string VARCHAR(64))

BEGIN

    DECLARE n INT DEFAULT 0;
    DECLARE i INT DEFAULT 0;
    DECLARE col_name VARCHAR(30) DEFAULT "";
    DECLARE col_datatype VARCHAR(10) DEFAULT "";
    DECLARE previous_col VARCHAR(30) DEFAULT col_name;

    SELECT COUNT(*) 
    FROM 
        (SELECT COLUMN_NAME 
        FROM INFORMATION_SCHEMA.COLUMNS 
        WHERE TABLE_NAME = table_name_string) AS TEMP 
    INTO n;

    SET @Q= CONCAT('ALTER TABLE `',database_name,'`.`',table_name_string,'` CHANGE COLUMN `',index_name_string,'` `',index_name_string,'` BIGINT(20) NOT NULL FIRST');
    PREPARE exe FROM @Q;
    EXECUTE exe;
    DEALLOCATE PREPARE exe;

    SET n = n-1;
    SET i=1;

    WHILE i<n DO 


        SELECT COLUMN_NAME FROM 
            (SELECT COLUMN_NAME, @row_num:= @row_num + 1 as ind_rows 
            FROM INFORMATION_SCHEMA.COLUMNS, (SELECT @row_num:= 0 AS num) AS c 
            WHERE TABLE_NAME = table_name_string AND COLUMN_NAME <> index_name_string 
            ORDER BY COLUMN_NAME ASC) as TEMP 
        WHERE ind_rows = i 
        INTO col_name;

        SELECT DATA_TYPE 
        FROM 
            (SELECT DATA_TYPE, @row_num:= @row_num + 1 as ind_rows 
            FROM INFORMATION_SCHEMA.COLUMNS, (SELECT @row_num:= 0 AS num) AS c 
            WHERE TABLE_NAME = table_name_string AND COLUMN_NAME <> index_name_string 
            ORDER BY COLUMN_NAME ASC) as TEMP 
        WHERE ind_rows = i 
        INTO col_datatype;

        IF i = 1 THEN
            SET previous_col = index_name_string;
        ELSE
            SELECT COLUMN_NAME 
            FROM 
                (SELECT COLUMN_NAME, @row_num:= @row_num + 1 as ind_rows 
                FROM INFORMATION_SCHEMA.COLUMNS, (SELECT @row_num:= 0 AS num) AS c 
                WHERE TABLE_NAME = table_name_string AND COLUMN_NAME <> index_name_string 
                ORDER BY COLUMN_NAME ASC) as TEMP 
            WHERE ind_rows = i-1
            INTO previous_col;
        END IF;

        IF col_datatype = 'varchar' THEN
            SET col_datatype = 'TEXT';
        END IF;

        select col_name, previous_col;
        IF col_name <> index_name_string OR index_name_string = '' THEN
            SET @Q= CONCAT('ALTER TABLE `',database_name,'`.`',table_name_string,'` CHANGE COLUMN `',col_name,'` `',col_name,'` ',col_datatype,' NULL DEFAULT NULL AFTER `',previous_col,'`');
            PREPARE exe FROM @Q;
            EXECUTE exe;
            DEALLOCATE PREPARE exe;
        END IF;
        SET i = i + 1;

    END WHILE;
END;
;;

DELIMITER ;

# NOTE: ASSUMES INDEX IS BIGINT(20), IF OTHER PLEASE ADAPT IN LINE 22 TO MEET DATATYPE
#
# CALL ALPHABETISE_TABLE_COLUMNS('database_name', 'column_name', 'index_name')

Hope this helps!

贪了杯 2024-10-07 02:10:24
ORDER BY COLUMN_NAME ASC;

请注意,COLUMN_NAME 函数用于引用表的列名。该功能并非在所有数据库系统中都可用,并且在某些情况下可能无法按预期工作。

ORDER BY COLUMN_NAME ASC;

Note that the COLUMN_NAME function is used to refer to the column names of the table. This function is not available in all database systems, and it may not work as expected in some cases.

っ左 2024-10-07 02:10:24

是的。可以使用以下命令。

SELECT column_name FROM user_tab_cols WHERE table_name=UPPER('Your_Table_Name') order by column_name;

它将按字母顺序显示表中的所有列。

Yes. It is possible with the following command.

SELECT column_name FROM user_tab_cols WHERE table_name=UPPER('Your_Table_Name') order by column_name;

It will display all columns of your table in alphabetic order.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文