zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

sqlserver导出插入脚本代码

SQLServer导出代码 脚本 插入
2023-06-13 09:14:32 时间
当然有其它工具可以做这件事,但如果客户不允许你在服务器乱装东西时这个脚本就会有用了。
复制代码代码如下:

DECLARE@tbImportTablestable(tablenamevarchar(128),deletedtinyint)

--appendtableswhichyouwanttoimport
InsertInto@tbImportTables(tablename,deleted)values("tentitytype",1)
InsertInto@tbImportTables(tablename,deleted)values("tattribute",1)
--appendalltables
--InsertInto@tbImportTables(tablename,deleted)selecttable_name,1fromINFORMATION_SCHEMA.tableswheretable_type="BASETABLE"

DECLARE@tbImportScriptstable(scriptvarchar(max))

Declare@tablenamevarchar(128),
@deletedtinyint,
@columnnamevarchar(128),
@fieldscriptvarchar(max),
@valuescriptvarchar(max),
@insertscriptvarchar(max)

DeclarecurImportTablesCursorFor
Selecttablename,deleted
From@tbImportTables

OpencurImportTables
FetchNextFromcurImportTablesInto@tablename,@deleted

WHILE@@Fetch_STATUS=0
Begin
  If(@deleted=1)
  begin
    Insertinto@tbImportScripts(script)values("Truncatetable"+@tablename)
  end

  Insertinto@tbImportScripts(script)values("SETIDENTITY_INSERT"+@tablename+"ON")

  set@fieldscript=""
  select@fieldscript=@fieldscript+column_name+","fromINFORMATION_SCHEMA.columnswheretable_name=@tablenameanddata_typenotin("timestamp","image")
  set@fieldscript=substring(@fieldscript,0,len(@fieldscript))

  set@valuescript=""
  select@valuescript=@valuescript+"casewhen"+column_name+"isnullthen""null""else""""""""+convert(varchar(max),"+column_name+")+""""""""end+"",""+"  fromINFORMATION_SCHEMA.columnswheretable_name=@tablenameanddata_typenotin("timestamp","image")
  set@valuescript=substring(@valuescript,0,len(@valuescript)-4)

  set@insertscript="select""insertinto"+@tablename+"("+@fieldscript+")values("+"""+"+@valuescript+"+"")""from"+@tablename
  Insertinto@tbImportScripts(script)exec(@insertscript)

  Insertinto@tbImportScripts(script)values("SETIDENTITY_INSERT"+@tablename+"OFF")

  Insertinto@tbImportScripts(script)values("GO")
  FetchNextFromcurImportTablesInto@tablename,@deleted
End

ClosecurImportTables
DeallocatecurImportTables

Select*from@tbImportScripts