如何将表中的所有数据导出为可插入的sql格式?

时间:2013-12-12 11:53:47

标签: sql sql-server copy export ssms

我在Microsoft SQL Server Management Studio的数据库(称为A_table)中有一个表(称之为A_db),共有10行。

我有另一个数据库(称之为B_db),它有一个表(称之为B_table),它具有与A_table相同的列设置。但是B_table是空的。

我想要的是什么:

  • 复制A_tableB_table的每一行。

Microsoft SQL Server Management Studio 2012 中是否有任何选项可以从表中创建插入SQL?或者还有其他选择吗?

7 个答案:

答案 0 :(得分:387)

快捷方式:

  1. 右键单击数据库
  2. 指向tasks In SSMS 2017 you need to ignore step 2 - the generate scripts options is at the top level of the context menu感谢Daniel更新评论。
  3. 选择generate scripts
  4. 点击下一步
  5. 选择表格
  6. 点击下一步
  7. 点击高级
  8. 滚动到data to script - 在SMSS 2014中调用types of data to script感谢Ellesedil发表评论
  9. 选择data only
  10. 单击“确定”关闭高级脚本选项窗口
  11. 单击“下一步”并生成脚本
  12. 我通常在这样的情况下生成一个新的查询编辑器窗口,然后在需要时进行任何修改。

答案 1 :(得分:7)

我知道这是一个老问题,但victorio还询问是否还有其他选项可以将数据从一个表复制到另一个表。将一个表中的所有记录插入另一个表(可能有也可能没有类似设计)的方法非常简短快捷。

如果您在表B_table中没有标识列:

INSERT INTO A_db.dbo.A_table
SELECT * FROM B_db.dbo.B_table

如果表B_table中有标识列,则必须指定要插入的列。基本上,您选择除标识列以外的所有标识列,默认情况下将自动递增。

如果您在B_db中没有现有的B_table

SELECT *
INTO B_db.dbo.B_table
FROM A_db.dbo.A_table

将在数据库B_db中创建具有所有现有值的表B_table

答案 2 :(得分:4)

通过DumpDataFromTable sproc将数据作为文件转储的另一种方法

EXEC dbo.DumpDataFromTable
     @SchemaName = 'dbo'
    ,@TableName = 'YourTableName'
    ,@PathOut = N'c:\tmp\scripts\' -- folder must exist !!!'

注意: SQL必须具有创建文件的权限,如果没有设置,则执行后续行

EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE WITH OVERRIDE;

通过此脚本,您可以调用sproc:DumpDataFromTable.sql并一次性转储更多表,而不是从Management Studio逐个手动执行

默认情况下,生成的脚本的格式类似于

INSERT INTO <TableName> SELECT <Values>

或者您可以将生成的格式更改为

SELECT ... FROM

通过设置变量@BuildMethod = 2

完整的代码:

    IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DumpDataFromTable]') AND type in (N'P', N'PC'))
        DROP PROCEDURE dbo.[DumpDataFromTable]
    GO

    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO

    -- =============================================
    -- Author:    Oleg Ciobanu
    -- Create date: 20171214
    -- Version 1.0
    -- Description:
    -- dump data in 2 formats
    -- @BuildMethod = 1 INSERT INTO format
    -- @BuildMethod = 2 SELECT * FROM format
    --
    -- SQL must have permission to create files, if is not set-up then exec follow line once
    -- EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE WITH OVERRIDE;
    --
    -- =============================================
    CREATE PROCEDURE [dbo].[DumpDataFromTable]
    (
         @SchemaName nvarchar(128) --= 'dbo'
        ,@TableName nvarchar(128) --= 'testTable'
        ,@WhereClause nvarchar (1000) = '' -- must start with AND
        ,@BuildMethod int = 1 -- taking values 1 for INSERT INTO forrmat or 2 for SELECT from value Table
        ,@PathOut nvarchar(250) = N'c:\tmp\scripts\' -- folder must exist !!!'
        ,@AsFileNAme nvarchar(250) = NULL -- if is passed then will use this value as FileName
        ,@DebugMode int = 0
    )
    AS
    BEGIN  
        SET NOCOUNT ON;

            -- run follow next line if you get permission deny  for sp_OACreate,sp_OAMethod
            -- EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE WITH OVERRIDE;

        DECLARE @Sql nvarchar (max)
        DECLARE @SqlInsert nvarchar (max) = ''
        DECLARE @Columns nvarchar(max)
        DECLARE @ColumnsCast nvarchar(max)

        -- cleanUp/prepraring data
        SET @SchemaName = REPLACE(REPLACE(@SchemaName,'[',''),']','')
        SET @TableName = REPLACE(REPLACE(@TableName,'[',''),']','')
        SET @AsFileNAme = NULLIF(@AsFileNAme,'')
        SET @AsFileNAme = REPLACE(@AsFileNAme,'.','_')
        SET @AsFileNAme = COALESCE(@PathOut + @AsFileNAme + '.sql', @PathOut + @SchemaName + ISNULL('_' + @TableName,N'') + '.sql')


        --debug
        IF @DebugMode = 1
            print @AsFileNAme

            -- Create temp SP what will be responsable for generating script files
        DECLARE @PRC_WritereadFile VARCHAR(max) =
            'IF EXISTS (SELECT * FROM sys.objects WHERE type = ''P'' AND name = ''PRC_WritereadFile'')
           BEGIN
              DROP  Procedure  PRC_WritereadFile
           END;'
        EXEC  (@PRC_WritereadFile)
           -- '  
        SET @PRC_WritereadFile =
        'CREATE Procedure PRC_WritereadFile (
            @FileMode INT -- Recreate = 0 or Append Mode 1
           ,@Path NVARCHAR(1000)
           ,@AsFileNAme NVARCHAR(500)
           ,@FileBody NVARCHAR(MAX)   
           )
        AS
            DECLARE @OLEResult INT
            DECLARE @FS INT
            DECLARE @FileID INT
            DECLARE @hr INT
            DECLARE @FullFileName NVARCHAR(1500) = @Path + @AsFileNAme

            -- Create Object
            EXECUTE @OLEResult = sp_OACreate ''Scripting.FileSystemObject'', @FS OUTPUT
            IF @OLEResult <> 0 BEGIN
                PRINT ''Scripting.FileSystemObject''
                GOTO Error_Handler
            END    

            IF @FileMode = 0 BEGIN  -- Create
                EXECUTE @OLEResult = sp_OAMethod @FS,''CreateTextFile'',@FileID OUTPUT, @FullFileName
                IF @OLEResult <> 0 BEGIN
                    PRINT ''CreateTextFile''
                    GOTO Error_Handler
                END
            END ELSE BEGIN          -- Append
                EXECUTE @OLEResult = sp_OAMethod @FS,''OpenTextFile'',@FileID OUTPUT, @FullFileName, 8, 0 -- 8- forappending
                IF @OLEResult <> 0 BEGIN
                    PRINT ''OpenTextFile''
                    GOTO Error_Handler
                END            
            END

            EXECUTE @OLEResult = sp_OAMethod @FileID, ''WriteLine'', NULL, @FileBody
            IF @OLEResult <> 0 BEGIN
                PRINT ''WriteLine''
                GOTO Error_Handler
            END     

            EXECUTE @OLEResult = sp_OAMethod @FileID,''Close''
            IF @OLEResult <> 0 BEGIN
                PRINT ''Close''
                GOTO Error_Handler
            END

            EXECUTE sp_OADestroy @FS
            EXECUTE sp_OADestroy @FileID

            GOTO Done

            Error_Handler:
                DECLARE @source varchar(30), @desc varchar (200)       
                EXEC @hr = sp_OAGetErrorInfo null, @source OUT, @desc OUT
                PRINT ''*** ERROR ***''
                SELECT OLEResult = @OLEResult, hr = CONVERT (binary(4), @hr), source = @source, description = @desc

           Done:
        ';
            -- '
        EXEC  (@PRC_WritereadFile) 
        EXEC PRC_WritereadFile 0 /*Create*/, '', @AsFileNAme, ''


        ;WITH steColumns AS (
            SELECT
                1 as rn,
                c.ORDINAL_POSITION
                ,c.COLUMN_NAME as ColumnName
                ,c.DATA_TYPE as ColumnType
            FROM INFORMATION_SCHEMA.COLUMNS c
            WHERE 1 = 1
            AND c.TABLE_SCHEMA = @SchemaName
            AND c.TABLE_NAME = @TableName
        )

        --SELECT *

           SELECT
                @ColumnsCast = ( SELECT
                                        CASE WHEN ColumnType IN ('date','time','datetime2','datetimeoffset','smalldatetime','datetime','timestamp')
                                            THEN
                                                'convert(nvarchar(1001), s.[' + ColumnName + ']' + ' , 121) AS [' + ColumnName + '],'
                                                --,convert(nvarchar, [DateTimeScriptApplied], 121) as [DateTimeScriptApplied]
                                            ELSE
                                                'CAST(s.[' + ColumnName + ']' + ' AS NVARCHAR(1001)) AS [' + ColumnName + '],'
                                        END
                                         as 'data()'                                  
                                        FROM
                                          steColumns t2
                                        WHERE 1 =1
                                          AND t1.rn = t2.rn
                                        FOR xml PATH('')
                                       )
                ,@Columns = ( SELECT
                                        '[' + ColumnName + '],' as 'data()'                                  
                                        FROM
                                          steColumns t2
                                        WHERE 1 =1
                                          AND t1.rn = t2.rn
                                        FOR xml PATH('')
                                       )

        FROM steColumns t1

        -- remove last char
        IF lEN(@Columns) > 0 BEGIN
            SET @Columns = SUBSTRING(@Columns, 1, LEN(@Columns)-1);
            SET @ColumnsCast = SUBSTRING(@ColumnsCast, 1, LEN(@ColumnsCast)-1);
        END

        -- debug
        IF @DebugMode = 1 BEGIN
            print @ColumnsCast
            print @Columns
            select @ColumnsCast ,  @Columns
        END

        -- build unpivoted Data
        SET @SQL = '
        SELECT
            u.rn
            , c.ORDINAL_POSITION as ColumnPosition
            , c.DATA_TYPE as ColumnType
            , u.ColumnName
            , u.ColumnValue
        FROM
        (SELECT
            ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS rn,
        '
        + CHAR(13) + @ColumnsCast
        + CHAR(13) + 'FROM [' + @SchemaName + '].[' + @TableName + '] s'
        + CHAR(13) + 'WHERE 1 = 1'
        + CHAR(13) + COALESCE(@WhereClause,'')
        + CHAR(13) + ') tt
        UNPIVOT
        (
          ColumnValue
          FOR ColumnName in (
        ' + CHAR(13) + @Columns
        + CHAR(13)
        + '
         )
        ) u

        LEFT JOIN INFORMATION_SCHEMA.COLUMNS c ON c.COLUMN_NAME = u.ColumnName
            AND c.TABLE_SCHEMA = '''+ @SchemaName + '''
            AND c.TABLE_NAME = ''' + @TableName +'''
        ORDER BY u.rn
                , c.ORDINAL_POSITION
        '

        -- debug
        IF @DebugMode = 1 BEGIN
            print @Sql     
        END

        EXEC (@Sql)

        -- prepare data for cursor

        IF OBJECT_ID('tempdb..#tmp') IS NOT NULL
            DROP TABLE #tmp
        CREATE TABLE #tmp
        (
            rn bigint
            ,ColumnPosition int
            ,ColumnType varchar (128)
            ,ColumnName varchar (128)
            ,ColumnValue nvarchar (2000) -- I hope this size will be enough for storring values
        )
        SET @Sql = 'INSERT INTO  #tmp ' + CHAR(13)  + @Sql

        -- debug
        IF @DebugMode = 1 BEGIN
            print @Sql
        END

        EXEC (@Sql)

        IF @DebugMode = 1 BEGIN
            SELECT * FROM #tmp
        END

        DECLARE @rn bigint
            ,@ColumnPosition int
            ,@ColumnType varchar (128)
            ,@ColumnName varchar (128)
            ,@ColumnValue nvarchar (2000)
            ,@i int = -1 -- counter/flag
            ,@ColumnsInsert varchar(max) = NULL
            ,@ValuesInsert nvarchar(max) = NULL

        DECLARE cur CURSOR FOR
        SELECT rn, ColumnPosition, ColumnType, ColumnName, ColumnValue
        FROM #tmp
        ORDER BY rn, ColumnPosition -- note order is really important !!!
        OPEN cur

        FETCH NEXT FROM cur
        INTO @rn, @ColumnPosition, @ColumnType, @ColumnName, @ColumnValue

        IF @BuildMethod = 1
        BEGIN
            SET @SqlInsert = ''
        END
        ELSE BEGIN
            SET @SqlInsert = 'SELECT *'
                            + CHAR(13) + 'FROM ('
                            + CHAR(13) + 'VALUES'
            EXEC PRC_WritereadFile 1 /*Add*/, '', @AsFileNAme, @SqlInsert
            SET @SqlInsert = NULL
        END

        SET @i = @rn

        WHILE @@FETCH_STATUS = 0
        BEGIN

            IF (@i <> @rn) -- is a new row
            BEGIN
                IF @BuildMethod = 1
                -- build as INSERT INTO -- as Default
                BEGIN
                    SET @SqlInsert = 'INSERT INTO [' + @SchemaName + '].[' + @TableName + '] ('
                                    + CHAR(13) + @ColumnsInsert + ')'
                                    + CHAR(13) + 'VALUES ('
                                    + @ValuesInsert
                                    + CHAR(13) + ')'
                END
                ELSE
                BEGIN
                    -- build as Table select
                    IF (@i <> @rn) -- is a new row
                    BEGIN
                        SET @SqlInsert = COALESCE(@SqlInsert + ',','') +  '(' + @ValuesInsert+ ')'
                        EXEC PRC_WritereadFile 1 /*Add*/, '', @AsFileNAme, @SqlInsert
                        SET @SqlInsert = '' -- in method 2 we should clear script
                    END            
                END
                -- debug
                IF @DebugMode = 1
                    PRINT @SqlInsert
                EXEC PRC_WritereadFile 1 /*Add*/, '', @AsFileNAme, @SqlInsert

                -- we have new row
                -- initialise variables
                SET @i = @rn
                SET @ColumnsInsert = NULL
                SET @ValuesInsert = NULL
            END

            -- build insert values
            IF (@i = @rn) -- is same row
            BEGIN
                SET @ColumnsInsert = COALESCE(@ColumnsInsert + ',','') + '[' + @ColumnName + ']'
                SET @ValuesInsert =  CASE                              
                                        -- date
                                        --WHEN
                                        --  @ColumnType IN ('date','time','datetime2','datetimeoffset','smalldatetime','datetime','timestamp')
                                        --THEN
                                        --  COALESCE(@ValuesInsert + ',','') + '''''' + ISNULL(RTRIM(@ColumnValue),'NULL') + ''''''
                                        -- numeric
                                        WHEN
                                            @ColumnType IN ('bit','tinyint','smallint','int','bigint'
                                                            ,'money','real','','float','decimal','numeric','smallmoney')
                                        THEN
                                            COALESCE(@ValuesInsert + ',','') + '' + ISNULL(RTRIM(@ColumnValue),'NULL') + ''
                                        -- other types treat as string
                                        ELSE
                                            COALESCE(@ValuesInsert + ',','') + '''' + ISNULL(RTRIM(@ColumnValue),'NULL') + ''''    
                                    END
            END


            FETCH NEXT FROM cur
            INTO @rn, @ColumnPosition, @ColumnType, @ColumnName, @ColumnValue

            -- debug
            IF @DebugMode = 1
            BEGIN
                print CAST(@rn AS VARCHAR) + '-' + CAST(@ColumnPosition AS VARCHAR)
            END
        END
        CLOSE cur
        DEALLOCATE cur

        IF @BuildMethod = 1
        BEGIN
            PRINT 'ignore'
        END
        ELSE BEGIN
            SET @SqlInsert = CHAR(13) + ') AS vtable '
                            + CHAR(13) + ' (' + @Columns
                            + CHAR(13) + ')'
            EXEC PRC_WritereadFile 1 /*Add*/, '', @AsFileNAme, @SqlInsert
            SET @SqlInsert = NULL
        END
    END

或可以从https://github.com/Zindur/MSSQL-DumpTable/tree/master/Scripts

下载

答案 3 :(得分:1)

从Linux机器终端获取数据库备份的命令。

sqlcmd -S localhost -U SA -Q "BACKUP DATABASE [demodb] TO DISK = N'/var/opt/mssql/data/demodb.bak' WITH NOFORMAT, NOINIT, NAME = 'demodb-full', SKIP, NOREWIND, NOUNLOAD, STATS = 10"

希望it帮助某人。

答案 4 :(得分:-2)

我们只需要使用以下查询将一个表数据转储到另一表中即可。

Select * into SampleProductTracking_tableDump
from SampleProductTracking;

SampleProductTracking_tableDump是一个新表,它将自动创建 与上面的查询一起使用时。 它将记录从SampleProductTracking复制到SampleProductTracking_tableDump

enter image description here

答案 5 :(得分:-3)

到目前为止,我还没有看到Microsoft SQL Server Management Studio 2012中的任何选项。

我确信你可以根据时间用T-SQL写一些东西。

查看TOAD from QUEST - 现在由DELL拥有。

http://www.toadworld.com/products/toad-for-oracle/f/10/t/9778.aspx

Select your rows.
Rt -click -> Export Dataset.
Choose Insert Statement format
Be sure to check “selected rows only”

关于toad的好处,它适用于SQL服务器和Oracle。如果你必须同时使用它们,这是一个很好的投资。

答案 6 :(得分:-3)

试试www.sqlscripter.com。

据我所知,它是唯一不仅仅创建一次INSERT脚本的工具,您还可以生成INSERT和UPDATE以及将脚本组合在一起以进行频繁更新。我们已经使用它几年了,它对我们来说非常完美。