简体   繁体   English

T-SQL如何创建一个结构在另一个表中的表?

[英]T-SQL how to create a table whose structure is in another table?

如何创建一个存储过程来创建一个表,其结构存储在另一个表中,当然还有s-sql和sql server?

T-SQL allows to create tables on the fly using SELECT * ... INTO syntax: T-SQL允许使用SELECT * ... INTO语法动态创建表:

SELECT * INTO TargetTable
FROM SourceTable
-- any false returning condition will do
WHERE 1 = 0

This can also be written elegantly (thanks to Deadsheep39 ): 这也可以写Deadsheep39优雅(感谢Deadsheep39 ):

SELECT TOP 0 * INTO TargetTable
FROM SourceTable

However, this will fail if TargetTable already exists, so you should check for its existence: 但是,如果TargetTable已经存在,这将失败,因此您应该检查它的存在:

IF OBJECT_ID('TheSchema.TargetTable') IS NOT NULL
    DROP TABLE TargetTable

Also, no indexes, constraints or trigger will be created. 此外,不会创建索引,约束或触发器。 Check here for more details. 点击此处了解更多详情。

If you want to go dynamic (table names are parameters) you can create and execute a dynamic query: 如果您想要动态(表名是参数),您可以创建并执行动态查询:

CREATE PROCEDURE dbo.GenerateTable
(
    @SourceTable VARCHAR(128),
    @TargetTable VARCHAR(128)
)    
AS
BEGIN
    DECLARE @SQL NVARCHAR(4000) = N'
        SELECT * INTO ' + QUOTENAME(@TargetTable) + '
        FROM ' + QUOTENAME(@SourceTable) + '
        -- any false returning condition will do
        WHERE 1 = 0'
    EXEC (@SQL)
END
GO

You can construct query as string with CREATE TABLE statement and execute it by using sp_executesql stored procedure. 您可以使用CREATE TABLE语句将查询构造为字符串,并使用sp_executesql存储过程执行它。

For instance in this way: 例如这样:

DECLARE @query nvarchar(max) = N'CREATE TABLE Table(Col nvarchar(50) NULL)'
EXECUTE sp_executesql @query

where in the @query variable you can build based on what kind of table you need. @query变量中,您可以根据所需的表格来构建。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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