将选择结果转换为插入脚本 - SQL Server

发布于 2024-10-08 22:08:24 字数 282 浏览 3 评论 0原文

我有 SQL Server 2008、SQL Server Management Studio。

我需要从一个数据库中的表中选择数据并将其插入到另一个数据库中的另一个表中。

如何将我的选择返回的结果转换为 INSERT INTO ...

评论澄清:虽然我相信这可以通过 INSERT INTO SELECTSELECT INTO 解决,但我确实需要生成 INSERT INTO ... >。

I have SQL Server 2008, SQL Server Management Studio.

I need to select data from a table in one database and insert into another table in another database.

How can I convert the returned results from my select into INSERT INTO ...?

Clarification from comments: While I believe this could be solved by a INSERT INTO SELECT or SELECT INTO, I do need to generate INSERT INTO ....

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(18

凉宸 2024-10-15 22:08:25

这是另一种方法,在某些情况下可能比安装插件或外部工具更容易:

  • 选择[您需要的任何内容]INTO temp.table_name来自[...等...]
  • 在对象资源管理器中右键单击数据库 =>任务=>生成脚本
  • 在“选择对象”屏幕中选择 temp.table_name,然后单击“下一步”。
  • 在“指定如何保​​存脚本”屏幕中:
    • 点击“高级”,找到“脚本数据类型”属性,选择“仅数据”,关闭高级属性。
    • 选择“保存到新查询窗口”(除非您有数千条记录)。
  • 单击“下一步”,等待作业完成,观察生成的 INSERT 语句出现在新的查询窗口中。
  • 使用“查找”替换以将所有 [temp.table_name] 更改为 [your_table_name]
  • 删除表[temp.table_name]

Here is another method, which may be easier than installing plugins or external tools in some situations:

  • Do a select [whatever you need]INTO temp.table_namefrom [... etc ...].
  • Right-click on the database in the Object Explorer => Tasks => Generate Scripts
  • Select temp.table_name in the "Choose Objects" screen, click Next.
  • In the "Specify how scripts should be saved" screen:
    • Click Advanced, find the "Types of data to Script" property, select "Data only", close the advanced properties.
    • Select "Save to new query window" (unless you have thousands of records).
  • Click Next, wait for the job to complete, observe the resulting INSERT statements appear in a new query window.
  • Use Find & Replace to change all [temp.table_name] to [your_table_name].
  • drop table [temp.table_name].
沧笙踏歌 2024-10-15 22:08:25

在SSMS中:

  • 右键单击数据库>任务>生成脚本

  • 下一步

  • 选择“选择特定数据库对象”并选中要编写脚本的表,下一步

  • 点击选项列表中的高级>,向下滚动到底部并查找“要编写脚本的数据类型”并将其更改为“仅数据”>确定

  • 选择“保存到新查询窗口”>下一页>下一页>完成

现在所有 180 行都写为 180 个插入语句!

In SSMS:

  • Right click on the database > Tasks > Generate Scripts

  • Next

  • Select "Select specific database objects" and check the table you want scripted, Next

  • Click Advanced > in the list of options, scroll down to the bottom and look for the "Types of data to script" and change it to "Data Only" > OK

  • Select "Save to new query window" > Next > Next > Finish

All 180 rows now written as 180 insert statements!

一生独一 2024-10-15 22:08:25

本机方法

例如,如果您有表,

Users(Id, name)

您可以这样做:

select 'insert into Table values(Id=' + Id + ', name=' + name + ')' from Users

Native method:

for example if you have table

Users(Id, name)

You can do this:

select 'insert into Table values(Id=' + Id + ', name=' + name + ')' from Users
彼岸花似海 2024-10-15 22:08:25

SSMS 工具包(就像啤酒一样免费)具有多种出色的功能 - 包括 从表生成 INSERT 语句

更新:对于 SQL Server Management Studio 2012(及更高版本),SSMS Toolpack 不再免费,但需要适度的许可费。

SSMS Toolpack (which is FREE as in beer) has a variety of great features - including generating INSERT statements from tables.

Update: for SQL Server Management Studio 2012 (and newer), SSMS Toolpack is no longer free, but requires a modest licensing fee.

骑趴 2024-10-15 22:08:25

1- 脚本说明

A) 在表中插入数据的语法如下

Insert into table(col1,col2,col3,col4,col5)    

             -- To achieve this part i    
             --have used below variable
                ------@CSV_COLUMN-------

values(Col1 data in quote, Col2..quote,..Col5..quote)

-- To achieve this part 
-- i.e column data in 
--quote i have used 
--below variable
----@QUOTED_DATA---

C) 从现有数据中获取上述数据
表我们必须写选择
以这样的方式查询输出
将采用上述脚本的形式

D)然后最后我连接了
上面要创建的变量
最终脚本将
在执行时生成插入脚本

E)

@TEXT='SELECT ''INSERT INTO
 '+@TABLE_NAME+'('+@CSV_COLUMN+')VALUES('''+'+'+SUBSTRING(@QUOTED_DATA,1,LEN(@QUOTED_DATA)-5)+'+'+''')'''+' Insert_Scripts FROM '+@TABLE_NAME + @FILTER_CONDITION

F)最后执行上述查询 EXECUTE(TEXT)

G)QUOTENAME() 函数用于包装
引号 H)ISNULL 内的列数据

使用 ,因为如果任何行具有 NULL
查询失败的任何列的数据
并返回 NULL 这就是为什么要避免
我已经使用了 ISNULL

I)并创建了 sp sp_generate_insertscripts
同样

1- 只需输入您想要插入脚本的表名称

2- 如果您想要特定结果,则过滤条件

----------Final Procedure To generate Script------

CREATE PROCEDURE sp_generate_insertscripts
(
    @TABLE_NAME VARCHAR(MAX),
    @FILTER_CONDITION VARCHAR(MAX)=''
)
AS
BEGIN

SET NOCOUNT ON

DECLARE @CSV_COLUMN VARCHAR(MAX),
        @QUOTED_DATA VARCHAR(MAX),
        @TEXT VARCHAR(MAX)

SELECT @CSV_COLUMN=STUFF
(
    (
     SELECT ',['+ NAME +']' FROM sys.all_columns 
     WHERE OBJECT_ID=OBJECT_ID(@TABLE_NAME) AND 
     is_identity!=1 FOR XML PATH('')
    ),1,1,''
)

SELECT @QUOTED_DATA=STUFF
(
    (
     SELECT ' ISNULL(QUOTENAME('+NAME+','+QUOTENAME('''','''''')+'),'+'''NULL'''+')+'','''+'+' FROM sys.all_columns 
     WHERE OBJECT_ID=OBJECT_ID(@TABLE_NAME) AND 
     is_identity!=1 FOR XML PATH('')
    ),1,1,''
)

SELECT @TEXT='SELECT ''INSERT INTO '+@TABLE_NAME+'('+@CSV_COLUMN+')VALUES('''+'+'+SUBSTRING(@QUOTED_DATA,1,LEN(@QUOTED_DATA)-5)+'+'+''')'''+' Insert_Scripts FROM '+@TABLE_NAME + @FILTER_CONDITION

--SELECT @CSV_COLUMN AS CSV_COLUMN,@QUOTED_DATA AS QUOTED_DATA,@TEXT TEXT

EXECUTE (@TEXT)

SET NOCOUNT OFF

END

1- Explanation of Scripts

A)Syntax for inserting data in table is as below

Insert into table(col1,col2,col3,col4,col5)    

             -- To achieve this part i    
             --have used below variable
                ------@CSV_COLUMN-------

values(Col1 data in quote, Col2..quote,..Col5..quote)

-- To achieve this part 
-- i.e column data in 
--quote i have used 
--below variable
----@QUOTED_DATA---

C)To get above data from existing
table we have to write the select
query in such way that the output
will be in form of as above scripts

D)Then Finally i have Concatenated
above variable to create
final script that's will
generate insert script on execution

E)

@TEXT='SELECT ''INSERT INTO
 '+@TABLE_NAME+'('+@CSV_COLUMN+')VALUES('''+'+'+SUBSTRING(@QUOTED_DATA,1,LEN(@QUOTED_DATA)-5)+'+'+''')'''+' Insert_Scripts FROM '+@TABLE_NAME + @FILTER_CONDITION

F)And Finally Executed the above query EXECUTE(TEXT)

G)QUOTENAME() function is used to wrap
column data inside quote

H)ISNULL is used because if any row has NULL
data for any column the query fails
and return NULL thats why to avoid
that i have used ISNULL

I)And created the sp sp_generate_insertscripts
for same

1- Just put the table name for which you want insert script

2- Filter condition if you want specific results

----------Final Procedure To generate Script------

CREATE PROCEDURE sp_generate_insertscripts
(
    @TABLE_NAME VARCHAR(MAX),
    @FILTER_CONDITION VARCHAR(MAX)=''
)
AS
BEGIN

SET NOCOUNT ON

DECLARE @CSV_COLUMN VARCHAR(MAX),
        @QUOTED_DATA VARCHAR(MAX),
        @TEXT VARCHAR(MAX)

SELECT @CSV_COLUMN=STUFF
(
    (
     SELECT ',['+ NAME +']' FROM sys.all_columns 
     WHERE OBJECT_ID=OBJECT_ID(@TABLE_NAME) AND 
     is_identity!=1 FOR XML PATH('')
    ),1,1,''
)

SELECT @QUOTED_DATA=STUFF
(
    (
     SELECT ' ISNULL(QUOTENAME('+NAME+','+QUOTENAME('''','''''')+'),'+'''NULL'''+')+'','''+'+' FROM sys.all_columns 
     WHERE OBJECT_ID=OBJECT_ID(@TABLE_NAME) AND 
     is_identity!=1 FOR XML PATH('')
    ),1,1,''
)

SELECT @TEXT='SELECT ''INSERT INTO '+@TABLE_NAME+'('+@CSV_COLUMN+')VALUES('''+'+'+SUBSTRING(@QUOTED_DATA,1,LEN(@QUOTED_DATA)-5)+'+'+''')'''+' Insert_Scripts FROM '+@TABLE_NAME + @FILTER_CONDITION

--SELECT @CSV_COLUMN AS CSV_COLUMN,@QUOTED_DATA AS QUOTED_DATA,@TEXT TEXT

EXECUTE (@TEXT)

SET NOCOUNT OFF

END
旧时光的容颜 2024-10-15 22:08:25

可以通过Visual Studio SQL Server 对象资源管理器来完成。

您可以从上下文菜单中单击“查看数据”以获取必要的表格、过滤结果并将结果另存为脚本。

It's possible to do via Visual Studio SQL Server Object Explorer.

You can click "View Data" from context menu for necessary table, filter results and save result as script.

红衣飘飘貌似仙 2024-10-15 22:08:25

使用 Visual Studio,执行以下操作

创建 SQL Server 类型的项目 --> SQL Server 数据库项目

打开 sql server explorer CTL-\ , CTL-S

通过右键单击 SQL SERVER 图标添加 SQL Server。选择添加新服务器

,导航到您感兴趣的表,

右键单击-->查看数据

单击左上角的单元格以突出显示所有内容(ctl-A 似乎不起作用)

右键单击​​ --> SCript

这太棒了。多年来我已经尝试过上面列出的所有内容。我知道有一个工具可以做到这一点以及更多,但想不出它的名字。但它非常昂贵。

祝你好运。我刚刚想通了这一点。还没有对它进行广泛的文本字段等测试,但看起来它会让你走得很远。

格雷格

Using visual studio, do the following

Create a project of type SQL Server-->SQL Server Database Project

open the sql server explorer CTL-\ , CTL-S

add a SQL Server by right clicking on the SQL SERVER icon. Selcet ADD NEW SERVER

navigate down to the table you are interested in

right click--> VIEW DATA

Click the top left cell to highlight everything (ctl-A doesnt seem to work)

Right Click -->SCript

This is fabulous. I have tried everything listed above over the years. I know there is a tool out there that will do this and much more, cant think of the name of it. But it is very expensive.

Good luck. I just figured this out. Have not tested it extensively w/ text fields etc, but it looks like it gets you a long ways down the road.

Greg

夜吻♂芭芘 2024-10-15 22:08:25

使用 into 语句创建一个单独的表
例如

Select * into Test_123 from [dbo].[Employee] where Name like '%Test%'

转到数据库
右键单击数据库
单击生成脚本
选择您的餐桌
选择高级选项并选择属性“仅数据”
选择文件“在新查询中打开”

Sql将为您生成脚本

Create a separate table using into statement
For example

Select * into Test_123 from [dbo].[Employee] where Name like '%Test%'

Go to the Database
Right Click the Database
Click on Generate Script
Select your table
Select advanace option and select the Attribute "Data Only"
Select the file "open in new query"

Sql will generate script for you

挽手叙旧 2024-10-15 22:08:25

这是一个更通用的解决方案(可以比问题所要求的多一点),并且可以在查询窗口中使用,而无需创建新的存储过程 - 在生产数据库中非常有用,例如您没有写访问权限的情况。

要使用该代码,请根据解释其用法的行内注释进行修改。然后,您可以在查询窗口中运行此查询,它将打印您需要的 INSERT 语句。

SET NOCOUNT ON

-- Set the ID you wish to filter on here
DECLARE @id AS INT = 123

DECLARE @tables TABLE (Name NVARCHAR(128), IdField NVARCHAR(128), IdInsert BIT, Excluded NVARCHAR(128))

-- Add any tables you wish to generate INSERT statements for here. The fields are as thus:
 -- Name: Your table name
 -- IdField: The field on which to filter the dataset
 -- IdInsert: If the primary key field is to be included in the INSERT statement
 -- Excluded: Any fields you do not wish to include in the INSERT statement
INSERT INTO @tables (Name, IdField, IdInsert, Excluded) VALUES ('MyTable1', 'Id', 0, 'Created,Modified')
INSERT INTO @tables (Name, IdField, IdInsert, Excluded) VALUES ('MyTable2', 'Id', 1, 'Created,Modified')

DECLARE @numberTypes TABLE (sysId TINYINT)

-- This will ensure INT and BIT types are not surrounded with quotes in the
-- resultant INSERT statement, but you may need to add more (from sys.types)
INSERT @numberTypes(SysId) VALUES(56),(104)

DECLARE @rows INT = (SELECT COUNT(*) FROM @tables)
DECLARE @cnt INT = 1

DECLARE @results TABLE (Sql NVARCHAR(4000))

WHILE @cnt <= @rows
BEGIN
    DECLARE @tablename AS NVARCHAR(128)
    DECLARE @idField AS NVARCHAR(128)
    DECLARE @idInsert AS BIT
    DECLARE @excluded AS NVARCHAR(128)
    SELECT
        @tablename = Name,
        @idField = IdField,
        @idInsert = IdInsert,
        @excluded = Excluded
    FROM (SELECT *, ROW_NUMBER() OVER(ORDER BY (SELECT 1)) AS RowId FROM @tables) t WHERE t.RowId = @cnt

    DECLARE @excludedFields TABLE (FieldName NVARCHAR(128))
    DECLARE @xml AS XML = CAST(('<X>' + REPLACE(@excluded, ',', '</X><X>') + '</X>') AS XML)
    INSERT INTO @excludedFields SELECT N.value('.', 'NVARCHAR(128)') FROM @xml.nodes('X') AS T(N)

    DECLARE @setIdentity NVARCHAR(128) = 'SET IDENTITY_INSERT ' + @tablename

    DECLARE @execsql AS NVARCHAR(4000) = 'SELECT ''' + CASE WHEN @idInsert = 1 THEN @setIdentity + ' ON' + CHAR(13) ELSE '' END + 'INSERT INTO ' + @tablename + ' ('
    SELECT @execsql = @execsql +
    STUFF
    (
        (
            SELECT CASE WHEN NOT EXISTS(SELECT * FROM @excludedFields WHERE FieldName = name) THEN ', ' + name ELSE '' END
            FROM sys.columns
            WHERE object_id = OBJECT_ID('dbo.' + @tablename)
            FOR XML PATH('')
        ), 1, 2, ''
    ) +
    ')' + CHAR(13) + 'VALUES (' +
    STUFF
    (
        (
            SELECT
                CASE WHEN NOT EXISTS(SELECT * FROM @excludedFields WHERE FieldName = name) THEN
                    ''', '' + ISNULL(' +
                    CASE WHEN EXISTS(SELECT * FROM @numberTypes WHERE SysId = system_type_id) THEN '' ELSE ''''''''' + ' END +
                    'CAST(' + name + ' AS VARCHAR)' +
                    CASE WHEN EXISTS(SELECT * FROM @numberTypes WHERE SysId = system_type_id) THEN '' ELSE ' + ''''''''' END +
                    ', ''NULL'') + '
                ELSE ''
                END
            FROM sys.columns
            WHERE object_id = OBJECT_ID('dbo.' + @tablename)
            FOR XML PATH('')
        ), 1, 3, ''
    ) +
    ''')' + CASE WHEN @idInsert = 1 THEN CHAR(13) + @setIdentity + ' OFF' ELSE '' END +
    ''' FROM ' + @tablename + ' WHERE ' + @idField + ' = ' + CAST(@id AS VARCHAR)

    INSERT @results EXEC (@execsql)
    DELETE @excludedFields
    SET @cnt = @cnt + 1
END

DECLARE cur CURSOR FOR SELECT Sql FROM @results
OPEN cur

DECLARE @sql NVARCHAR(4000)
FETCH NEXT FROM cur INTO @sql
WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT @sql
    FETCH NEXT FROM cur INTO @sql
END

CLOSE cur
DEALLOCATE cur

This is a more versatile solution (that can do a little more than the question asks), and can be used in a query window without having to create a new stored proc - useful in production databases for instance where you don't have write access.

To use the code, please modify according to the in line comments which explain its usage. You can then just run this query in a query window and it will print the INSERT statements you require.

SET NOCOUNT ON

-- Set the ID you wish to filter on here
DECLARE @id AS INT = 123

DECLARE @tables TABLE (Name NVARCHAR(128), IdField NVARCHAR(128), IdInsert BIT, Excluded NVARCHAR(128))

-- Add any tables you wish to generate INSERT statements for here. The fields are as thus:
 -- Name: Your table name
 -- IdField: The field on which to filter the dataset
 -- IdInsert: If the primary key field is to be included in the INSERT statement
 -- Excluded: Any fields you do not wish to include in the INSERT statement
INSERT INTO @tables (Name, IdField, IdInsert, Excluded) VALUES ('MyTable1', 'Id', 0, 'Created,Modified')
INSERT INTO @tables (Name, IdField, IdInsert, Excluded) VALUES ('MyTable2', 'Id', 1, 'Created,Modified')

DECLARE @numberTypes TABLE (sysId TINYINT)

-- This will ensure INT and BIT types are not surrounded with quotes in the
-- resultant INSERT statement, but you may need to add more (from sys.types)
INSERT @numberTypes(SysId) VALUES(56),(104)

DECLARE @rows INT = (SELECT COUNT(*) FROM @tables)
DECLARE @cnt INT = 1

DECLARE @results TABLE (Sql NVARCHAR(4000))

WHILE @cnt <= @rows
BEGIN
    DECLARE @tablename AS NVARCHAR(128)
    DECLARE @idField AS NVARCHAR(128)
    DECLARE @idInsert AS BIT
    DECLARE @excluded AS NVARCHAR(128)
    SELECT
        @tablename = Name,
        @idField = IdField,
        @idInsert = IdInsert,
        @excluded = Excluded
    FROM (SELECT *, ROW_NUMBER() OVER(ORDER BY (SELECT 1)) AS RowId FROM @tables) t WHERE t.RowId = @cnt

    DECLARE @excludedFields TABLE (FieldName NVARCHAR(128))
    DECLARE @xml AS XML = CAST(('<X>' + REPLACE(@excluded, ',', '</X><X>') + '</X>') AS XML)
    INSERT INTO @excludedFields SELECT N.value('.', 'NVARCHAR(128)') FROM @xml.nodes('X') AS T(N)

    DECLARE @setIdentity NVARCHAR(128) = 'SET IDENTITY_INSERT ' + @tablename

    DECLARE @execsql AS NVARCHAR(4000) = 'SELECT ''' + CASE WHEN @idInsert = 1 THEN @setIdentity + ' ON' + CHAR(13) ELSE '' END + 'INSERT INTO ' + @tablename + ' ('
    SELECT @execsql = @execsql +
    STUFF
    (
        (
            SELECT CASE WHEN NOT EXISTS(SELECT * FROM @excludedFields WHERE FieldName = name) THEN ', ' + name ELSE '' END
            FROM sys.columns
            WHERE object_id = OBJECT_ID('dbo.' + @tablename)
            FOR XML PATH('')
        ), 1, 2, ''
    ) +
    ')' + CHAR(13) + 'VALUES (' +
    STUFF
    (
        (
            SELECT
                CASE WHEN NOT EXISTS(SELECT * FROM @excludedFields WHERE FieldName = name) THEN
                    ''', '' + ISNULL(' +
                    CASE WHEN EXISTS(SELECT * FROM @numberTypes WHERE SysId = system_type_id) THEN '' ELSE ''''''''' + ' END +
                    'CAST(' + name + ' AS VARCHAR)' +
                    CASE WHEN EXISTS(SELECT * FROM @numberTypes WHERE SysId = system_type_id) THEN '' ELSE ' + ''''''''' END +
                    ', ''NULL'') + '
                ELSE ''
                END
            FROM sys.columns
            WHERE object_id = OBJECT_ID('dbo.' + @tablename)
            FOR XML PATH('')
        ), 1, 3, ''
    ) +
    ''')' + CASE WHEN @idInsert = 1 THEN CHAR(13) + @setIdentity + ' OFF' ELSE '' END +
    ''' FROM ' + @tablename + ' WHERE ' + @idField + ' = ' + CAST(@id AS VARCHAR)

    INSERT @results EXEC (@execsql)
    DELETE @excludedFields
    SET @cnt = @cnt + 1
END

DECLARE cur CURSOR FOR SELECT Sql FROM @results
OPEN cur

DECLARE @sql NVARCHAR(4000)
FETCH NEXT FROM cur INTO @sql
WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT @sql
    FETCH NEXT FROM cur INTO @sql
END

CLOSE cur
DEALLOCATE cur
倾其所爱 2024-10-15 22:08:25

我创建了以下过程

if object_id('tool.create_insert', 'P') is null
begin
  exec('create procedure tool.create_insert as');
end;
go

alter procedure tool.create_insert(@schema    varchar(200) = 'dbo',
                                   @table     varchar(200),
                                   @where     varchar(max) = null,
                                   @top       int = null,
                                   @insert    varchar(max) output)
as
begin
  declare @insert_fields varchar(max),
          @select        varchar(max),
          @error         varchar(500),
          @query         varchar(max);

  declare @values table(description varchar(max));

  set nocount on;

  -- Get columns
  select @insert_fields = isnull(@insert_fields + ', ', '') + c.name,
         @select = case type_name(c.system_type_id)
                      when 'varchar' then isnull(@select + ' + '', '' + ', '') + ' isnull('''''''' + cast(' + c.name + ' as varchar) + '''''''', ''null'')'
                      when 'datetime' then isnull(@select + ' + '', '' + ', '') + ' isnull('''''''' + convert(varchar, ' + c.name + ', 121) + '''''''', ''null'')'
                      else isnull(@select + ' + '', '' + ', '') + 'isnull(cast(' + c.name + ' as varchar), ''null'')'
                    end
    from sys.columns c with(nolock)
         inner join sys.tables t with(nolock) on t.object_id = c.object_id
         inner join sys.schemas s with(nolock) on s.schema_id = t.schema_id
   where s.name = @schema
     and t.name = @table;

  -- If there's no columns...
  if @insert_fields is null or @select is null
  begin
    set @error = 'There''s no ' + @schema + '.' + @table + ' inside the target database.';
    raiserror(@error, 16, 1);
    return;
  end;

  set @insert_fields = 'insert into ' + @schema + '.' + @table + '(' + @insert_fields + ')';

  if isnull(@where, '') <> '' and charindex('where', ltrim(rtrim(@where))) < 1
  begin
    set @where = 'where ' + @where;
  end
  else
  begin
    set @where = '';
  end;

  set @query = 'select ' + isnull('top(' + cast(@top as varchar) + ')', '') + @select + ' from ' + @schema + '.' + @table + ' with (nolock) ' + @where;

  insert into @values(description)
  exec(@query);

  set @insert = isnull(@insert + char(10), '') + '--' + upper(@schema + '.' + @table);

  select @insert = @insert + char(10) + @insert_fields + char(10) + 'values(' + v.description + ');' + char(10) + 'go' + char(10)
    from @values v
   where isnull(v.description, '') <> '';
end;
go

然后您可以这样使用它:

declare @insert varchar(max),
        @part   varchar(max),
        @start  int,
        @end    int;

set @start = 1;

exec tool.create_insert @schema = 'dbo',
                        @table = 'customer',
                        @where  = 'id = 1',
                        @insert = @insert output;

-- Print one line to avoid the maximum 8000 characters problem
while len(@insert) > 0
begin
  set @end = charindex(char(10), @insert);

  if @end = 0
  begin
    set @end = len(@insert) + 1;
  end;

  print substring(@insert, @start, @end - 1);
  set @insert = substring(@insert, @end + 1, len(@insert) - @end + 1);
end;

输出将类似于:

--DBO.CUSTOMER
insert into dbo.customer(id, name, type)
values(1, 'CUSTOMER NAME', 'F');
go

如果您只想获取一系列行,请使用@top 参数如下:

declare @insert varchar(max),
        @part   varchar(max),
        @start  int,
        @end    int;

set @start = 1;

exec tool.create_insert @schema = 'dbo',
                        @table = 'customer',
                        @top    = 100,
                        @insert = @insert output;

-- Print one line to avoid the maximum 8000 characters problem
while len(@insert) > 0
begin
  set @end = charindex(char(10), @insert);

  if @end = 0
  begin
    set @end = len(@insert) + 1;
  end;

  print substring(@insert, @start, @end - 1);
  set @insert = substring(@insert, @end + 1, len(@insert) - @end + 1);
end;

I created the following procedure:

if object_id('tool.create_insert', 'P') is null
begin
  exec('create procedure tool.create_insert as');
end;
go

alter procedure tool.create_insert(@schema    varchar(200) = 'dbo',
                                   @table     varchar(200),
                                   @where     varchar(max) = null,
                                   @top       int = null,
                                   @insert    varchar(max) output)
as
begin
  declare @insert_fields varchar(max),
          @select        varchar(max),
          @error         varchar(500),
          @query         varchar(max);

  declare @values table(description varchar(max));

  set nocount on;

  -- Get columns
  select @insert_fields = isnull(@insert_fields + ', ', '') + c.name,
         @select = case type_name(c.system_type_id)
                      when 'varchar' then isnull(@select + ' + '', '' + ', '') + ' isnull('''''''' + cast(' + c.name + ' as varchar) + '''''''', ''null'')'
                      when 'datetime' then isnull(@select + ' + '', '' + ', '') + ' isnull('''''''' + convert(varchar, ' + c.name + ', 121) + '''''''', ''null'')'
                      else isnull(@select + ' + '', '' + ', '') + 'isnull(cast(' + c.name + ' as varchar), ''null'')'
                    end
    from sys.columns c with(nolock)
         inner join sys.tables t with(nolock) on t.object_id = c.object_id
         inner join sys.schemas s with(nolock) on s.schema_id = t.schema_id
   where s.name = @schema
     and t.name = @table;

  -- If there's no columns...
  if @insert_fields is null or @select is null
  begin
    set @error = 'There''s no ' + @schema + '.' + @table + ' inside the target database.';
    raiserror(@error, 16, 1);
    return;
  end;

  set @insert_fields = 'insert into ' + @schema + '.' + @table + '(' + @insert_fields + ')';

  if isnull(@where, '') <> '' and charindex('where', ltrim(rtrim(@where))) < 1
  begin
    set @where = 'where ' + @where;
  end
  else
  begin
    set @where = '';
  end;

  set @query = 'select ' + isnull('top(' + cast(@top as varchar) + ')', '') + @select + ' from ' + @schema + '.' + @table + ' with (nolock) ' + @where;

  insert into @values(description)
  exec(@query);

  set @insert = isnull(@insert + char(10), '') + '--' + upper(@schema + '.' + @table);

  select @insert = @insert + char(10) + @insert_fields + char(10) + 'values(' + v.description + ');' + char(10) + 'go' + char(10)
    from @values v
   where isnull(v.description, '') <> '';
end;
go

Then you can use it that way:

declare @insert varchar(max),
        @part   varchar(max),
        @start  int,
        @end    int;

set @start = 1;

exec tool.create_insert @schema = 'dbo',
                        @table = 'customer',
                        @where  = 'id = 1',
                        @insert = @insert output;

-- Print one line to avoid the maximum 8000 characters problem
while len(@insert) > 0
begin
  set @end = charindex(char(10), @insert);

  if @end = 0
  begin
    set @end = len(@insert) + 1;
  end;

  print substring(@insert, @start, @end - 1);
  set @insert = substring(@insert, @end + 1, len(@insert) - @end + 1);
end;

The output would be something like that:

--DBO.CUSTOMER
insert into dbo.customer(id, name, type)
values(1, 'CUSTOMER NAME', 'F');
go

If you just want to get a range of rows, use the @top parameter as bellow:

declare @insert varchar(max),
        @part   varchar(max),
        @start  int,
        @end    int;

set @start = 1;

exec tool.create_insert @schema = 'dbo',
                        @table = 'customer',
                        @top    = 100,
                        @insert = @insert output;

-- Print one line to avoid the maximum 8000 characters problem
while len(@insert) > 0
begin
  set @end = charindex(char(10), @insert);

  if @end = 0
  begin
    set @end = len(@insert) + 1;
  end;

  print substring(@insert, @start, @end - 1);
  set @insert = substring(@insert, @end + 1, len(@insert) - @end + 1);
end;
好倦 2024-10-15 22:08:25

您可以在 SSMS 中选择“结果到文件”选项,并将选择结果导出到文件,并在结果文件中进行更改,最后使用 BCP - 批量复制,您可以插入数据库 2 的表 1 中。

我认为对于批量插入,您必须将 .rpt 文件转换为 .csv 文件

希望它会有所帮助。

You can Choose 'Result to File' option in SSMS and export your select result to file and make your changes in result file and finally using BCP - Bulk copy you can insert in table 1 in database 2.

I think for bulk insert you have to convert .rpt file to .csv file

Hope it will help.

江南烟雨〆相思醉 2024-10-15 22:08:25

我遇到了类似的问题,但我需要能够从查询(带有过滤器等)创建 INSERT 语句,

因此我创建了以下过程:

CREATE PROCEDURE dbo.ConvertQueryToInsert (@input NVARCHAR(max), @target NVARCHAR(max)) AS BEGIN

    DECLARE @fields NVARCHAR(max);
    DECLARE @select NVARCHAR(max);

    -- Get the defintion from sys.columns and assemble a string with the fields/transformations for the dynamic query
    SELECT
        @fields = COALESCE(@fields + ', ', '') + '[' + name +']', 
        @select = COALESCE(@select + ', ', '') + ''''''' + ISNULL(CAST([' + name + '] AS NVARCHAR(max)), ''NULL'')+'''''''
    FROM tempdb.sys.columns 
    WHERE [object_id] = OBJECT_ID(N'tempdb..'+@input);

    -- Run the a dynamic query with the fields from @select into a new temp table
    CREATE TABLE #ConvertQueryToInsertTemp (strings nvarchar(max))
    DECLARE @stmt NVARCHAR(max) = 'INSERT INTO #ConvertQueryToInsertTemp SELECT '''+ @select + ''' AS [strings] FROM '+@input
    exec sp_executesql @stmt

    -- Output the final insert statement 
    SELECT 'INSERT INTO ' + @target + ' (' + @fields + ') VALUES (' + REPLACE(strings, '''NULL''', 'NULL') +')' FROM #ConvertQueryToInsertTemp

    -- Clean up temp tables
    DROP TABLE #ConvertQueryToInsertTemp
    SET @stmt = 'DROP TABLE ' + @input
    exec sp_executesql @stmt
END

然后您可以通过将查询的输出写入临时表并运行来使用它程序:

-- Example table
CREATE TABLE Dummy (Id INT, Comment NVARCHAR(50), TimeStamp DATETIME)
INSERT INTO Dummy VALUES (1 , 'Foo', GetDate()), (2, 'Bar', GetDate()), (3, 'Foo Bar', GetDate())

-- Run query and procedure
SELECT * INTO #TempTableForConvert FROM Dummy WHERE Id < 3
EXEC dbo.ConvertQueryToInsert '#TempTableForConvert', 'dbo.Dummy'

注意:
此过程仅将值转换为字符串,这可能会导致数据看起来有点不同。例如,对于 DATETIME,秒数将会丢失。

I had a similar problem, but I needed to be able to create an INSERT statement from a query (with filters etc.)

So I created following procedure:

CREATE PROCEDURE dbo.ConvertQueryToInsert (@input NVARCHAR(max), @target NVARCHAR(max)) AS BEGIN

    DECLARE @fields NVARCHAR(max);
    DECLARE @select NVARCHAR(max);

    -- Get the defintion from sys.columns and assemble a string with the fields/transformations for the dynamic query
    SELECT
        @fields = COALESCE(@fields + ', ', '') + '[' + name +']', 
        @select = COALESCE(@select + ', ', '') + ''''''' + ISNULL(CAST([' + name + '] AS NVARCHAR(max)), ''NULL'')+'''''''
    FROM tempdb.sys.columns 
    WHERE [object_id] = OBJECT_ID(N'tempdb..'+@input);

    -- Run the a dynamic query with the fields from @select into a new temp table
    CREATE TABLE #ConvertQueryToInsertTemp (strings nvarchar(max))
    DECLARE @stmt NVARCHAR(max) = 'INSERT INTO #ConvertQueryToInsertTemp SELECT '''+ @select + ''' AS [strings] FROM '+@input
    exec sp_executesql @stmt

    -- Output the final insert statement 
    SELECT 'INSERT INTO ' + @target + ' (' + @fields + ') VALUES (' + REPLACE(strings, '''NULL''', 'NULL') +')' FROM #ConvertQueryToInsertTemp

    -- Clean up temp tables
    DROP TABLE #ConvertQueryToInsertTemp
    SET @stmt = 'DROP TABLE ' + @input
    exec sp_executesql @stmt
END

You can then use it by writing the output of your query into a temp table and running the procedure:

-- Example table
CREATE TABLE Dummy (Id INT, Comment NVARCHAR(50), TimeStamp DATETIME)
INSERT INTO Dummy VALUES (1 , 'Foo', GetDate()), (2, 'Bar', GetDate()), (3, 'Foo Bar', GetDate())

-- Run query and procedure
SELECT * INTO #TempTableForConvert FROM Dummy WHERE Id < 3
EXEC dbo.ConvertQueryToInsert '#TempTableForConvert', 'dbo.Dummy'

Note:
This procedure only casts the values to a string which can cause the data to look a bit different. With DATETIME for example the seconds will be lost.

偷得浮生 2024-10-15 22:08:25

您可以使用专为导入和导出操作设计的Sql Server集成服务包

如果你完全安装了Sql Server,VS有一个用于开发这些包的包。

Business Intelligence Development Studio 中的集成服务

You can Use Sql Server Integration Service Packages specifically designed for Import and Export operation.

VS has a package for developing these packages if your fully install Sql Server.

Integration Services in Business Intelligence Development Studio

蓝梦月影 2024-10-15 22:08:25

我认为使用即席查询也是可能的
您可以将结果导出到 excel 文件,然后将该文件导入到数据表对象中,或者按原样使用它,然后将 excel 文件导入到第二个数据库中
看看这个链接
这可以帮助你很多。

http://vscontrols.blogspot.com /2010/09/import-and-export-excel-to-sql-server.html

I think its also possible with adhoc queries
you can export result to excel file and then import that file into your datatable object or use it as it is and then import the excel file into the second database
have a look at this link
this can help u alot.

http://vscontrols.blogspot.com/2010/09/import-and-export-excel-to-sql-server.html

请恋爱 2024-10-15 22:08:25

如果您使用的是 Oracle(或将应用程序配置到 SQL Server),则 Oracle SQL Developer 会为您执行此操作。为表选择“卸载”并按照选项进行操作(如果您不希望所有表创建内容,请取消选中 DDL)。

If you are using Oracle (or configure the application to the SQL Server) then Oracle SQL Developer does this for you. choose 'unload' for a table and follow the options through (untick DDL if you don't want all the table create stuff).

夏花。依旧 2024-10-15 22:08:25

您可以使用这个Q2C.SSMSPlugin,它是免费且开源的。您可以右键单击并选择“执行查询命令... -> 查询插入...”。享受)

You can use this Q2C.SSMSPlugin, which is free and open source. You can right click and select "Execute Query To Command... -> Query To Insert...". Enjoy)

蓝咒 2024-10-15 22:08:25

我发现了这个 SSMS Boost 插件,它是免费的并且确实可以做到这一点。您可以右键单击结果并选择将数据脚本为。

I found this SSMS Boost addon, which is free and does exactly this among other things. You can right click on the results and select Script data as.

荒岛晴空 2024-10-15 22:08:25

您可以使用 INSERT INTO SELECT 语句将选择查询的结果插入表中。 http://www.w3schools.com/sql/sql_insert_into_select.asp

示例:

INSERT INTO Customers (CustomerName, Country)
SELECT SupplierName, Country
FROM Suppliers
WHERE Country='Germany'

You can use an INSERT INTO SELECT statement, to insert the results of a select query into a table. http://www.w3schools.com/sql/sql_insert_into_select.asp

Example:

INSERT INTO Customers (CustomerName, Country)
SELECT SupplierName, Country
FROM Suppliers
WHERE Country='Germany'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文