How to use dynamic SQL to return the combined query data of temporary tables

Source: Internet
Author: User
 
Create Table # TABLE (Num int, name1 nvarchar (10), name2 nvarchar (10) Create Table # Table1 (Num int, name1 nvarchar (10 )) insert into # Table1 select 1, 'A' Union all select 2, 'B' CREATE TABLE # Table2 (num1 int, name2 nvarchar (10) insert into # Table2 select 1, 'A' Union all select 2, 'bb' declare @ sqlstr nvarchar (1000) -- set @ sqlstr = 'select. *, B. name2 from # Table1 as a inner join # Table2 as B on. num = B. num1 'insert into # Table exec (@ sqlstr) Select * from # tabledrop table # table1drop table # table2drop table # Table
 
According to the above method, if there is such a situation:
 
1. Data is queried by a combination of multiple temporary tables to form a large table. Data in a large table, such as a primary key, cannot be duplicated.
 
2. The column fields in the temporary table are not fixed and may be randomly generated.
 
Solution:
 
1. Use @ SQL to dynamically create a new large table, which contains the dynamic column fields to be generated.
 
2. Use dynamic SQL combined query syntax.
 
3. Execute the query syntax using exec to load the result set to the big table.

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.