SQL Server dynamically creates temporary table statements

Source: Internet
Author: User

Therefore, we plan to insert data into a temporary table before analyzing the data in the temporary table.
The problem is how to dynamically create a temporary table. Originally, Insus. NET was implemented using the following code:
Copy codeThe Code is 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, a function [dbo]. [Column] () is used to obtain a series of dynamic fields.
In fact, the above Code has no problem at all. It is capable of creating a temporary table correctly and dynamically. However, in the code below, we cannot use this temporary table [dbo]. [# Tb], because the process has ended after running the EXECUTE (@ s) 10th line code. In this case, it makes no sense to dynamically create a temporary table.
To solve this problem, Insus. NET came up with a method that could solve this problem. This temporary table can be created dynamically and can be used later.

Copy codeThe Code is 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)


If you have read this carefully, you can know that you can create the temporary table as usual, and then modify the field of the temporary table dynamically. After this is done, the temporary table can continue to be used after the program runs 10th lines of code, such:
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.