Can I logically reorder columns in a table?

后端 未结 8 1529
抹茶落季
抹茶落季 2020-12-15 02:04

If I\'m adding a column to a table in Microsoft SQL Server, can I control where the column is displayed logically in queries?

I don\'t want to mess with the physical

相关标签:
8条回答
  • 2020-12-15 03:01

    You can not do this programatically (in a safe way that is) without creating a new table.

    What Enterprise Manager does when you commit a reordering is to create a new table, move the data and then delete the old table and rename the new table to the existing name.

    If you want your columns in a particular order/grouping without altering their physical order, you can create a view which can be whatever you desire.

    0 讨论(0)
  • 2020-12-15 03:02

    There is one way, but its only temporarily for the query itself. For example,

    Lets say you have 5 tables. Table is called T_Testing

    FirstName, LastName, PhoneNumber, Email, and Member_ID

    you want it to list their ID, then Last Name, then FirstName, then Phone then Email.

    You can do it as per the Select.

    Select Member_ID, LastName, FirstName, PhoneNumber, Email
    From T_Testing
    

    Other than that, if you just want the LastName to Show before first name for some reason, you can do it also as follows:

    Select LastName, *
    From T_Testing
    

    The only thing you wanna be sure that you do is that the OrderBy or Where Function needs to be denoted as Table.Column if you are going to be using a Where or OrderBy

    Example:

    Select LastName, *
    From T_Testing
    Order By T_Testing.LastName Desc
    

    I hope this helps, I figured it out because I needed to do this myself.

    0 讨论(0)
提交回复
热议问题