在项目中,经常会遇到一个数据库访问另一个数据库,【CNVFERPDB】为服务器名,【CE3】为库名
1 SELECT Dtl.* 2 FROM CNVFERPDB. CE3.ce3.ZTLE0125 Dtl 3 INNER JOIN CNVFERPDB.CE3.ce3.ZTLE0124 Mst 4 ON Dtl.RECVSUPPNO = Mst.RECVSUPPNO AND Dtl.MANDT = Mst.MANDT 5 WHERE Mst.MANDT = '100' and Dtl.BRANDCODE='MD'
上面的方式是通过服务器名和库名直接访问,这样有多次连接另一个服务器,执行速度会很慢
可以换做下面的形式,执行速度将得到提升:
1 SELECT * 2 FROM OPENQUERY (CNVFERPDB 3 , 4 ' 5 SELECT Dtl.* 6 FROM CE3.ce3.ZTLE0125 Dtl 7 INNER JOIN CE3.ce3.ZTLE0124 Mst 8 ON Dtl.RECVSUPPNO = Mst.RECVSUPPNO AND Dtl.MANDT = Mst.MANDT 9 WHERE Mst.MANDT = ''100'' and Dtl.BRANDCODE=''MD'' 10 ' 11 )
OPENQUERY ( linked_server ,'query' )
使用注意事项:
linked_server
表示链接服务器名称的标识符。
'query'
在链接服务器中执行的查询字符串。 该字符串的最大长度为 8 KB。
补充
1 declare @Day VARCHAR(10)=CONVERT(CHAR(8),DATEADD(DAY,-1,GETDATE()),112) 2 3 --set @Day='20140605' 4 5 IF EXISTS(select * from AppLog where Dates=@Day) 6 return 7 8 declare @sql VARCHAR(2000)='select * 9 INTO #temp 10 from openquery 11 ([CNSASPLOGDB01], 12 '' 13 select 14 A.ProgramId 15 ,'''''+@Day+''''' AS Dates 16 ,COUNT(Duration) as Count 17 ,SUM(CAST(Duration AS DECIMAL(12,3)))/1000 AS SumTime 18 ,AVG(CAST(Duration AS DECIMAL(12,3)))/1000 as AvgTime 19 ,MAX(CAST(Duration AS DECIMAL(12,3)))/1000 as MaxTime 20 from 21 ( 22 select * from LogCSLK01.dbo.AppLog_'+@Day+' with(nolock) 23 union 24 select * from LogCSLK02.dbo.AppLog_'+@Day+' with(nolock) 25 union 26 select * from LogCSLK03.dbo.AppLog_'+@Day+' with(nolock) 27 ) A 28 group by A.ProgramId 29 '' 30 ) 31 32 insert into AppLog 33 select * 34 from #temp 35 36 drop table #temp 37 ' 38 --print @sql 39 40 exec(@sql)