简体   繁体   中英

T-SQL - Include table name (or alias) concatenated with column name in result set?

Using SSMS when joining 3+ tables and using SELECT * , I'm wondering if there is an easy way (dynamic) to include the table name & column name in the result set without having to type out all the desired columns.

For example:

Table1
Table2
Table3
SELECT *
FROM Table1 t1
LEFT JOIN Table2 t2 ON t2.keyA = t1.keyA
LEFT JOIN Table3 t3 ON t2.keyB = t3.keyB

Trying to produce output like

Table1-Column1, Table2-Column1, Table3-Column1

OR

t1.Column1, t2.Column1, t3.Column1

If you have a lot of column, there's is an easy way to do it, but not dynamically. If you have only a few columns, doesn't worth a try and do it manually.

Take a look at theses two methods: https://blog.sqlauthority.com/2012/06/06/sql-server-tricks-to-replace-select-with-column-names-sql-in-sixty-seconds-017-video/

First method (drag'n'drop columns) isn't useful in your case cause we need to have all column aligned on different lines. The second (generating the create table script) is the one we need.

Generate the create table for table1 and copy-paste the columns needed from table1 into your query, and repeat for table2 and table3. Make sure they are all aligned in the same editor column.

Then, "the magic trick", simply press and hold the Alt key, click between the coma and the first letter of the first column name of t1 and drag to select the lines between the first column of t1 to the last column of t1. Type "t1.". That's it. repeat for t2 and t3.

This is not sql-server related, nor SSMS, but works with any decent editor supporting multiline editing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM