How does SQL Server determine the order of the columns when you do a `SELECT *`?

…衆ロ難τιáo~ 提交于 2020-01-13 07:59:26

问题


How does SQL Server determine the order of the columns when you do a SELECT *?

I know "Order By" is essential for ordering the data, but I expected the column names to be consistent.

Note: My code is not dependent on the actual order the columns are returned. I just want to know how SQL Server decides to order the column names.

Of about 20 computers my team is using, one of them behaves differently. Any difference deserves to be investigated. The column name ordering appears to be the same for all computers when we open SQL Server Management Studio. When our application makes a query is when I see the difference.

I am using SQL Server 2008, and SQL Server 2008 R2. My application uses C# System.Data.SqlClient to access the database.

EDIT: My problem turned out to be that one of the computers was configured to log in as 'sa', instead of the intended user. The query was hitting the table directly when we intended it to hit a view. Thanks for the help learning about sys.columns


回答1:


They are in the order of column_id from the system view sys.columns.

You can check it by:

SELECT column_id, name
FROM sys.columns
WHERE object_id = Object_id('MyTableName')
ORDER BY column_id

EDIT

This is for Dems. You should test on a larger table, but it looks like it uses the order defined in the table, not the index:

CREATE TABLE #T (cola int, colb int, colc int)

INSERT INTO #T
VALUES
(1,2,3),
(2,3,4),
(4,5,6)

SELECT * FROM #T

CREATE INDEX ix_test ON #T (colb, colc, cola)

SELECT * FROM #t
WHERE colb > 0

DROP TABLE #T



回答2:


They will be the same order in which they appear in Sql Server Management Studio; essentially, the order in which they were created.

The "correct" solution for assuring a desired column order is to specify the fields explicitly in your SELECT statement. SELECT * makes no guarantees about the ordering of output columns.



来源:https://stackoverflow.com/questions/10214114/how-does-sql-server-determine-the-order-of-the-columns-when-you-do-a-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!