日期:2014-05-18  浏览次数:20706 次

把一张表的数据批量插入到另外一张表
VBScript code
 <% 
Server.ScriptTimeOut=600
Set conn=Server.CreateObject("ADODB.Connection")
if err.number <>0 then
err.clear
  else
conn.open "Driver={SQL Server};Server=local,1433;UID=sa;PWD=!~@~@#$$432234$$543!;database=DATA;"
  end if

set rs=server.createobject("adodb.recordset")
rs.open "select CI_Keywords from TE_CorpInfo where ci_id > 13000 and ci_id <14000",conn,1,1 
if not rs.eof and not rs.bof then
for i=1 to rs.recordcount
'response.Write(rs.recordcount)
'response.end
aaa= rs.fields("CI_Keywords").value
bbb=split(aaa," ")
for j=1 to ubound(bbb)-1
set rskey = server.CreateObject("Adodb.Recordset")
rskey.open "select * from SS",conn,1,3
rskey.addnew
rskey("KeyName")= bbb(j)
rskey.update
rskey.close
set rskey=nothing
next
rs.movenext
next
end if
rs.close
conn.close
set conn=nothing
response.Write("success1~~~")
%>


这是一段asp的代码,实现的功能是把TE_CorpInfo的CI_Keywords字段的信息存放到一张新表SS的KeyName字段中去。因为CI_Keywords字段的组成是(a b c d)这种模式,要把CI_Keywords的内容以空格为分隔符,分别存入到SS的KeyName。因为TE_CorpInfo这张表的数据有4万多条,所以执行这段代码,会超过响应时间,虽然我设置了10分钟,后来我只能限制每次的数量为1000条,但是这样效率太低,而且执行速度还是不理想。所以,我想把上述代码改成 纯 SQL的代码,去服务器SQL端执行,但是SQL代码我不是很懂,不知道怎么写来实现这个功能,所以请教各位SQL大侠···

在线等···急急急···

------解决方案--------------------
SQL code
拆分表: 

--> --> (Roy)生成測試數據

if not object_id('Tab') is null
  drop table Tab
Go
Create table Tab([Col1] int,[COl2] nvarchar(5))
Insert Tab
select 1,N'a,b,c' union all
select 2,N'd,e' union all
select 3,N'f'
Go

SQL2000用辅助表:
if object_id('Tempdb..#Num') is not null
  drop table #Num
go
select top 100 ID=Identity(int,1,1) into #Num from syscolumns a,syscolumns b
Select
  a.Col1,COl2=substring(a.Col2,b.ID,charindex(',',a.Col2+',',b.ID)-b.ID)
from
  Tab a,#Num b
where
  charindex(',',','+a.Col2,b.ID)=b.ID --也可用 substring(','+a.COl2,b.ID,1)=','


SQL2005用Xml:

select
  a.COl1,b.Col2
from
  (select Col1,COl2=convert(xml,' <root> <v>'+replace(COl2,',',' </v> <v>')+' </v> </root>') from Tab)a
outer apply
  (select Col2=C.v.value('.','nvarchar(100)') from a.COl2.nodes('/root/v')C(v))b


SQL05用CTE:

;with roy as
(select Col1,COl2=cast(left(Col2,charindex(',',Col2+',')-1) as nvarchar(100)),Split=cast(stuff(COl2+',',1,charindex(',',Col2+','),'') as nvarchar(100)) from Tab
union all
select Col1,COl2=cast(left(Split,charindex(',',Split)-1) as nvarchar(100)),Split= cast(stuff(Split,1,charindex(',',Split),'') as nvarchar(100)) from Roy where split>''
)
select COl1,COl2 from roy order by COl1 option (MAXRECURSION 0)

生成结果:
/*
Col1    COl2
----------- -----
1      a
1      b
1      c
2      d
2      e
3      f
*/