Передача данных SQL - PullRequest
       7

Передача данных SQL

3 голосов
/ 20 декабря 2008

Мне нужно перенести данные из одной таблицы в ту же таблицу на другом сервере, который был усечен. Какой самый простой способ сделать это?

Ответы [ 6 ]

5 голосов
/ 20 декабря 2008

Настройка связанных серверов , а затем использовать следующее в целевой базе данных:

INSERT INTO existingTable (col1,col2..)

SELECT col1,col2...
FROM linkedserver.dbo.database.othertable
2 голосов
/ 20 декабря 2008

Резервное копирование таблицы на одном сервере в файл и восстановление этого файла в пустую таблицу на другом ...

2 голосов
/ 20 декабря 2008

Используйте мастер импорта и экспорта SQL Server. Вероятно, это самый простой способ выполнить эту задачу.

Для более сложной передачи данных рассмотрите использование утилиты bcp, оператора BULK INSERT и OPENDATASOURCE.

0 голосов
/ 08 марта 2012

Это сценарий, который мне нравится использовать для этого. Прост в использовании и в основном не содержит ошибок. Просто скопируйте приведенный ниже текст в окно запроса и следуйте инструкциям. После его запуска у вас будет куча операторов вставки, которые вы можете запустить на другом сервере.


/*
Use this script to create insert statements for each row in the specified table.

Instructions:
1. Set the database you want to script from as normal.

2. change the set @TableName = '<YourTableName>' line to be the
table you want to script out.

3. Run the script and copy all the text from the results below
the line with all the dashes (----).

Notes:
   If you get the error message "Invalid object name '<YourTableName>'."
   then you either forgot to set the correct database or you spelled
   your table name wrong

Credits:
  Bob Wiechman - Fix for smalldatetime support
  Richard Lesh - correct support of uniqueidentifiers, automatic
        setting of Identity off/on, add Where clause support, more detail in
      debug mode.
*/

declare @TableName sysname
declare @WhereClause  varchar(1024)
declare @IdentityInsert int
declare @ColName sysname
declare @ColType tinyint
declare @ColStatus tinyint
declare @DebugMode bit
declare @ColList nvarchar(4000)
declare @ValList nvarchar(4000)
declare @SQL1 nvarchar(1000)
declare @SQL2 nchar(10)
declare @SQL3 nchar(1000)

set @TableName = '<YourTableName>' --  '<YourTableName>'
set @WhereClause = ''               -- limit scope of inserts
set @DebugMode = 0                  -- set to 1 if you only want a script

set @IdentityInsert = 0                -- set to 1 if you want to force IDENTITY_INSERT statements

set @ColList = ''
set @ValList = ''
set @SQL1 = 'select replace(''insert into ' + @TableName + ' ('
set @SQL2 = ') values ('
set @SQL3 = ')'', ''''''null'''''', ''null'') from ' + @TableName

if @DebugMode = 1 print '-- StmtShell: ' + @sql1 + @sql2 + @sql3

declare csrColumns cursor local fast_forward for
  select c.name, c.xtype, c.status
  from syscolumns c
    inner join sysobjects o
      on o.id = c.id
  where o.name = @TableName
    and o.xtype in ('U', 'S')
  order by ColID

open csrColumns
fetch next from csrColumns into @ColName, @ColType, @ColStatus

while @@fetch_status = 0
begin
  set @ColList = @ColList + ' ' + @ColName
  if @ColType in (173, 104, 106, 62, 56, 60, 108, 59, 52, 122, 48, 165)    -- numeric types (nulls not supported yet)
    set @ValList = @ValList + ' ''+convert(varchar(200),' + @ColName + ')+'''
  else if @ColType in (175, 239, 231, 231, 167)                            -- uid and string types
    set @ValList = @ValList + ' ''''''+isnull(' + @ColName + ',''null'')+'''''''
  else if @ColType in (58, 61)                                             -- dates (nulls not supported yet)
    set @ValList = @ValList + ' ''''''+convert(varchar(200),' + @ColName + ')+'''''''
  else if @ColType = 36                                                    -- uniqueidentfiers (nulls not supported yet)
    set @ValList = @ValList + ' ''''{''+convert(varchar(200),' + @ColName + ')+''}'''''
  if @DebugMode = 1             begin print '-- @ValList: ' + rtrim(@ValList) end
  if (@ColStatus & 0x80) = 0x80 begin set @IdentityInsert = 1 end          -- Check if column has Identity attribute
  fetch next from csrColumns into @ColName, @ColType, @ColStatus
end

close csrColumns
deallocate csrColumns

set @ColList = replace(ltrim(@ColList), ' ', ', ')
set @ValList = replace(ltrim(@ValList), ' ', ', ')

if @IdentityInsert = 1
  print 'set identity_insert ' + @TableName + ' on'

if @DebugMode = 1
  print @SQL1 + @ColList + @SQL2 + @ValList + @SQL3 + ' ' + @WhereClause
else
  exec (@SQL1 + @ColList + @SQL2 + @ValList + @SQL3 + ' ' + @WhereClause)

if @IdentityInsert = 1
  print 'set identity_insert ' + @TableName + ' off'
0 голосов
/ 02 июля 2009

В зависимости от объема и частоты вашей передачи данных. Если это небольшой объем однократного процесса, лучше использовать T-SQL для прямой вставки данных. Это можно сделать либо через связанные серверы, либо с помощью предложения OPENQUERY.

В случае однократной обработки большого объема используйте утилиту SSIS или BCP.

Если высокая громкость, высокая частота, используйте репликацию.

0 голосов
/ 20 декабря 2008

Я бы использовал службы преобразования данных (иначе называемые службами интеграции).

...