Thursday 30 July 2015

Quickest way to SELECT and Query All Columns from a Table in SQL Server

Most of you, who are working on T-SQL must be knowing that using “SELECT * FROM <<Table>>” syntax is treated as a Bad Practice and instead, using “SELECT <<Column Names>> FROM <<Table>>” syntax is recommended as a Best Practice for various reasons .

Say you want to select all the columns from a table, for which you would write a query something like this:
SELECT *
FROM dbo.DimProduct
Now, as specified above, we need to replace the asterisk (*) in the above query with the list of all the columns present in DimProduct table. To do this, follow these steps:
  • Go to SSMS, Open a new query window, Type SELECT followed by a space on First Line and FROM dbo.DimProduct on the Second Line.
  • Go to Object Explorer | Database Containing DimProduct Table | DimProduct Table
  • Expand the DimProduct table and click on Columns folder
  • Hold the Left Mouse Button and Drag the Columns folder on to the Query Window after SELECT, which will pull all the columns from DimProduct table and place them after the SELECT statement in the query window separated by commas (,) as shown below.
Drag the Columns Folder to Right of SELECT Clause
When you drag the Columns folder, All the Columns from DimProduct are placed after the SELECT Clause and before the FROM Clause in the above query window as shown below.
Comma Seperated Columns Inserted between SELECT and FROM Clause

Now, you can make slight formatting changes to suit your needs and if you want, you can even remove some of the columns based on your need (Remember that, removal is always easier than addition when it comes to Coding and hence this approach!).

No comments:

Post a Comment