sqlserver 삽입 스 크 립 트 코드 내 보 내기

2885 단어 내 보 내기 삽입
물론 다른 도구 가 이 일 을 할 수 있 지만,고객 이 서버 에 물건 을 함부로 설치 하 는 것 을 허락 하지 않 는 다 면 이 스 크 립 트 는 유용 할 것 입 니 다
 
DECLARE @tbImportTables table(tablename varchar(128), deleted tinyint)

-- append tables which you want to import
Insert Into @tbImportTables(tablename, deleted) values('tentitytype', 1)
Insert Into @tbImportTables(tablename, deleted) values('tattribute', 1)
-- append all tables
--Insert Into @tbImportTables(tablename, deleted) select table_name, 1 from INFORMATION_SCHEMA.tables where table_type = 'BASE TABLE'

DECLARE @tbImportScripts table(script varchar(max))

Declare @tablename varchar(128),
@deleted tinyint,
@columnname varchar(128),
@fieldscript varchar(max),
@valuescript varchar(max),
@insertscript varchar(max)

Declare curImportTables Cursor For
Select tablename, deleted
From @tbImportTables

Open curImportTables
Fetch Next From curImportTables Into @tablename, @deleted

WHILE @@Fetch_STATUS = 0
Begin
  If (@deleted = 1)
  begin
    Insert into @tbImportScripts(script) values ('Truncate table ' + @tablename)
  end

  Insert into @tbImportScripts(script) values ('SET IDENTITY_INSERT ' + @tablename + ' ON')

  set @fieldscript = ''
  select @fieldscript = @fieldscript + column_name + ',' from INFORMATION_SCHEMA.columns where table_name = @tablename and data_type not in('timestamp', 'image')
  set @fieldscript = substring(@fieldscript, 0, len(@fieldscript))

  set @valuescript = ''
  select @valuescript = @valuescript + 'case when ' + column_name + ' is null then ''null'' else '''''''' + convert(varchar(max), ' + column_name + ') + '''''''' end +'',''+'   from INFORMATION_SCHEMA.columns where table_name = @tablename and data_type not in('timestamp', 'image')
  set @valuescript = substring(@valuescript, 0, len(@valuescript) - 4)

  set @insertscript = 'select ''insert into ' + @tablename + '(' + @fieldscript + ') values(' + '''+' + @valuescript + ' + '')'' from ' + @tablename
  Insert into @tbImportScripts(script) exec ( @insertscript)

  Insert into @tbImportScripts(script) values ('SET IDENTITY_INSERT ' + @tablename + ' OFF')

  Insert into @tbImportScripts(script) values ('GO ')
  Fetch Next From curImportTables Into @tablename, @deleted
End

Close curImportTables
Deallocate curImportTables

Select * from @tbImportScripts

좋은 웹페이지 즐겨찾기