SQL Server连接远程数据源
SQL Server连接远程数据源的基本方法有下面三种:
OPENDATASOURCE
: The OPENDATASOURCE function is used to
specify connection information for a remote data source by specifying
the OLE DB provider and an initialization string. OPENDATASOURCE can be
used directly within a SELECT, INSERT, UPDATE, or DELETE statement.
OPENROWSET
: The OPENROWSET function is used to specify
connection information for a remote data source and the name of an
object that will return a result set (such as a stored procedure) or a
query that will return a result set. Like OPENDATASOURCE, OPENROWSET
can be used directly within a SELECT, INSERT, UPDATE, or DELETE
statement.
Linked servers
: A linked server is an object within SQL
Server that defines the connection properties of another SQL Server.
When defined, queries can connect to the remote server using a
four-part name, such as
SQLSrv1.AdventureWorks.person.Contact
The four-part name identifies the server (SQLSrv1), the database
(AdventureWorks), the schema (Person), and the object (Contact table).
Linked servers are explored in more depth in the final section of this
chapter.
其中OPENDATASOURCE和OPENROWSET方法一般用来做临时查询(ad hoc query),如果需要经常的查询远程数据,则建议创建linked servers。但是,默认情况ad hoc query 是禁用的,需要手动启动:
sp_configure ‘show advanced options’, 1;
GO
RECONFIGURE;
GO
sp_configure ‘Ad hoc Distributed Queries’, 1;
GO
RECONFIGURE;
然后,就可以使用OPENDATASOURCE 查询远程数据库了,OPENDATASOURCE 基本语法如下:OPENDATASOURCE ( provider_name, init_string )。示例代码如下:
SELECT *
from OPENDATASOURCE(‘SQLNCLI’,
‘Data Source=SQL08;Integrated Security=SSPI’)
.Sales.dbo.Customers
上述代码从SQL08服务器上读取Sales数据库的Customers表的内容。
也可以通过OPENROWSET方法查询远程数据库,OPENROWSET和OPENDATASOURCE方法相似,基本的差异是
OPENROWSET总是返回结果集,而OPENDATASOURCE方法除了可以返回结果
相关文档:
在网上找了很多,总是不知道怎么用,于是自己写了一个:
declare @strHex char(5),
@len int,
@intOut int,
@i int,
@charint int
set @strHex = '20'
set @len = len(rtrim(@strHex))
set @i = 1
set @intOut = 0
while @i <= @len
begin
set @charint = case substring(upper(rtrim(ltrim(@strHex))) ......
SQL Server 2000中,有三个比较类似的功能:他们分别是:SCOPE_IDENTITY、IDENT_CURRENT 和 @@IDENTITY,它们都返回插入到 IDENTITY 列中的值。
IDENT_CURRENT 返回为任何会话和任何作用域中的特定表最后生成的标识值。IDENT_CURRENT 不受作用域和会话的限制,而受限于指定的表。IDENT_CURRENT 返回为任何会话和作用域中的 ......
select * into destTbl from srcTbl
insert into destTbl(fld1, fld2) select fld1, 5 from srcTbl
以上两句都是将 srcTbl 的数据插入到 destTbl,但两句又有区别的:
第一句(select into from)要求目标表(destTbl)不存在,因为在插入时会自动创建。
第二句(insert into select from)要求目标表(dest ......
SQL Server DATEDIFF() 函数
定义和用法
DATEDIFF() 函数返回两个日期之间的天数。
语法
DATEDIFF(datepart,startdate,enddate)
startdate 和 enddate 参数是合法的日期表达式。
datepart 参数可以是下列的值:
datepart缩写
年
yy, yyyy
季度
qq, q
月
mm, m
年中的日
dy, y
日
dd, d
周
wk, ww
星期
......
SQL Server的一些系统变量
sp_configure 'min server memory' --服务器最小内存gosp_configure 'max server memory' --服务器最大内存'gosp_configure 'index create memory'--创建索引占用的内存go--sp_configure 'min memory per query'--每次查询占用的最小内存
--获取I/O工作情况select -- @@id_bus ......