Multiple tables in SQL Server are used to obtain the same column and different columns (the answer is from the SQL expert's answer on csdn)

Source: Internet
Author: User
Find all columns with the same column name (regardless of type and accuracy) from different tables. Note that the number 3 in the last column is the number of tables to be queried.
Select a. Name, count (1) as TT from syscolumns A, sysobjects B
Where a. ID = B. ID and B. xtype = 'U' and B. Name in ('table _ 1', 'table _ 2', 'table _ 3 ')
Group by A. Name
Having count (1) = 3;

After the same columns are obtained from different tables, the results returned after the same columns are removed from each table.

Create view test
As
Select a. Name, count (1) as TT from syscolumns A, sysobjects B
Where a. ID = B. ID and B. xtype = 'U' and B. Name in ('table _ 1', 'table _ 2', 'table _ 3 ')
Group by A. Name
Having count (1) = 3;
Go
Select a. Name as column name
From syscolumns A, sysobjects B
Where B. xtype = 'U' and A. ID = B. ID and B. Name in ('table _ 1') and A. name not in (Select name from test)
Group by B. Name, A. Name having count (1) = 1

Drop view test

Original post address: How to query the same columns in N tables and different columns in each table (N is not fixed and the table structure is unpredictable)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.