如何将表模式和约束复制到不同数据库的表?

Him*_*dri 3 sql schema sql-server-2005

可以使用什么SQL将指定表的模式复制到不同数据库中的表?

And*_*mar 15

SELECT INTO将创建一个具有相同模式的新表.所以你可以:

 SELECT *
 INTO newdb.dbo.newtable
 FROM olddb.dbo.oldtable
Run Code Online (Sandbox Code Playgroud)

要复制架构而不是数据:

 SELECT TOP 0 *
 INTO newdb.dbo.newtable
 FROM olddb.dbo.oldtable
Run Code Online (Sandbox Code Playgroud)

这不会复制索引或键.要复制它们,请右键单击SQL Sever Management Studio中的表,然后选择"脚本表为".这将为您提供可以在新数据库上运行的脚本.

  • 我已经尝试了这个,但我还需要复制约束,我需要sql查询.谢谢你的帖子. (3认同)
  • 它不复制约束!它只对简单的副本有帮助。 (3认同)
  • -1这是不正确和危险的.这不会复制约束 (2认同)

小智 12

肯定是2年后,但想要提供解决方案.此过程将表复制到"BackUp_ <YYYYMMDD> _ <原始表名称>及其主键约束.它使用通配符'%'包围表名,以便允许复制一组表.我只是移动了主键,因为不依赖于其他表,因此不那么令人头疼.此外,没有游标!

ALTER PROCEDURE dbo.Admin_CopyTable
     @TableName NVARCHAR(255)
AS
BEGIN

    -- SET NOCOUNT ON added to prevent extra result sets from interfering with SELECT statements.
    SET NOCOUNT ON;

    -- is there any work to do?
    IF NOT (isNull(@TableName,'')='')
    BEGIN
        -- Get list of all tables that match the @TableName wildcard
        DECLARE @tables TABLE (id BIGINT IDENTITY(1,1), [name] NVARCHAR(255)) -- using id as means to avoid cursor
        INSERT INTO @tables SELECT table_name FROM information_schema.tables WHERE table_name LIKE '%' + @TableName + '%' AND table_name NOT LIKE 'BackUp_%' ORDER BY table_name

        -- Go through each table and copy it
        DECLARE @row BIGINT;
        DECLARE @thisTable AS NVARCHAR(255);
        DECLARE @dSQL  NVARCHAR(4000);      -- holds the SQL string to execute and copy table data
        DECLARE @TablePrefix NVARCHAR(255); -- Name that is prepended before the name of the actual table to show it is a backup table

        -- set default prefix by adding todays date to the table name
        SELECT @TablePrefix = 'BackUp_' + CONVERT(NVARCHAR(10), GetDate(), 112) + '_'; -- Date as YYYYMMDD

        -- Get first row for looping through list of tables
        SELECT @row = MIN(id) FROM @tables;

        WHILE (isNull(@row, 0) <> 0)    -- returns null when no more rows, which gets converted to 0 (zero)
        BEGIN
            SELECT @thisTable = [name] FROM @tables where id = @row

            IF NOT EXISTS(SELECT table_name FROM information_schema.tables WHERE table_name like @TablePrefix + @thisTable)
              BEGIN
                SET @dSQL = 'Select * Into ' + @TablePrefix + @thisTable + ' from ' + @thisTable;
                EXEC (@dSQL)
                PRINT @TablePrefix + @thisTable + ': Data Backed up.'

                -- Copy the Primary Key into the Backup table
                BEGIN   
                    -- Get list of all the columns that make up the Primary Key
                    -- for composite PK's = one row per pk column
                    DECLARE @PKColsTbl table ([name] NVARCHAR(255), col NVARCHAR(255))

                    INSERT INTO @PKColsTbl
                    SELECT  c.Constraint_Name, c.COLUMN_NAME  
                    FROM    INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk 
                           ,INFORMATION_SCHEMA.KEY_COLUMN_USAGE c 
                    WHERE   pk.TABLE_NAME = @thisTable 
                        and CONSTRAINT_TYPE = 'PRIMARY KEY' 
                        and c.TABLE_NAME = pk.TABLE_NAME 
                        and c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME 

                    -- Transpose rows into one column as a comma delimeted string
                    DECLARE @pkCol NVARCHAR(255);
                    SELECT @pkCol = stuff((select ',' + col from @PKColsTbl for XML PATH('')), 1,1,'')

                    -- Build the dynamic SQL statement and execute it
                    SET @dSQL = 'ALTER TABLE ' + @TablePrefix + @thisTable + ' ADD CONSTRAINT ' + 'PK_' + @TablePrefix + @thisTable + ' PRIMARY KEY (' + @pkCol + ')'
                    EXEC (@dSQL)
                    PRINT @TablePrefix + @thisTable + ': PK Created.'

                    -- Since its a loop, clear out the table
                    DELETE FROM @PKColsTbl
                END
                -- END of Copying the Primary Key

              END
            ELSE 
              BEGIN
                PRINT @TablePrefix + @thisTable + ': Exists!'
              END

            -- Get next row
            SELECT @row = min(id) FROM @tables WHERE id > @row
        END
    END
END
Run Code Online (Sandbox Code Playgroud)


pri*_*kar 5

尝试使用SQL SERVER SCRIPT WIZARD

1)选择一个数据库

2)右键单击 - >任务 - >生成脚本

3)单击下一步 - >,然后在选择数据库屏幕中,选择表(默认情况下将选中).检查"编写所选数据库中的所有对象".

4)单击"完成".

希望这可以帮助