SQL Server statement sharing for dynamically creating temporary tables _mssql

Source: Internet
Author: User
Therefore, the plan first inserts the data into a temporary table, and then analyzes the data for the temporary table.
The question point is how to create a temporary table dynamically. The original insus.net was implemented using the following code:
Copy Code code as follows:

DECLARE @s NVARCHAR (MAX) = '
IF object_id (' [dbo].[ #Tb] is not NULL
DROP TABLE [dbo]. [#Tb]
CREATE TABLE [dbo]. [#Tb]
(
[XXX] INT,
[XXX] NVARCHAR (50),
' + [dbo]. [Column] () + '
)'
EXECUTE (@s)


In the code above, there is a function [dbo]. [Column] () is to get a series of dynamic fields.
In fact, the above code is not a problem, is able to dynamically create a temporary table, but the next code, we can no longer use this temporary table [dbo]. [#Tb] because after the action of Run line 10th code execute (@s), the process is over. In this way, the dynamic creation of the temporary table, also has no meaning.
To solve this problem, insus.net thought of a way to solve the problem. It can be created dynamically and can continue to use this temporary table after it has been created.

Copy Code code as follows:

IF object_id (' [dbo].[ #Tb] is not NULL
DROP TABLE [dbo]. [#Tb]
CREATE TABLE [dbo]. [#Tb]
(
[XXX] INT,
[XXX] NVARCHAR (50)
)
DECLARE @tb NVARCHAR (MAX) = ' ALTER TABLE [dbo]. [#Tb] ADD ' + [dbo]. [Column] ()
EXECUTE (@tb)


As long as a careful look, you can know, you can create this temporary table, and then dynamically modify the temporary table fields. After you do this, you can continue to use the temporary table after the program has run through the 10th line of code, such as:
SELECT * FROM [dbo]. [#Tb]
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.