首先要使用openRowSet必须将sqlserver功能的外围配置中的openRowSet启用。我们看看这个sql语句
SELECT a.*
FROM OPENROWSET('SQLOLEDB','192.168.1.107\sql2k5';'sa';'123',
'SELECT * FROM data_center.bycommon.LogicEquipment') AS a
FROM OPENROWSET('SQLOLEDB','192.168.1.107\sql2k5';'sa';'123',
'SELECT * FROM data_center.bycommon.LogicEquipment') AS a
这段sql语句的意思是按照ole的方式访问sqlserver数据库,服务期为192.168.1.107\sql2k5,用户名为sa,密码为123。查询的数据是data_center数据库下的bycommon.LogicEquipment表.
这个函数具体有什么作用呢?我觉得在我们的项目里最重要的是数据同步。通过OPENROWSET函数你可以很简单的把一个数据库里面的某张表的数据插入到另外一个数据库的一张表。如:
insert into 另一个数据库服务器某张同样结构的表 SELECT a.*
FROM OPENROWSET('SQLOLEDB','192.168.1.107\sql2k5';'sa';'123',
'SELECT * FROM data_center.bycommon.LogicEquipment') AS a
FROM OPENROWSET('SQLOLEDB','192.168.1.107\sql2k5';'sa';'123',
'SELECT * FROM data_center.bycommon.LogicEquipment') AS a
下来我们看看如何使用row_Number。rownumber实现对行的自动编号
SELECT * FROM(SELECT *,ROW_NUMBER() OVER (ORDER BY plantId DESC) AS RowNumber FROM [bycommon].LogicEquipment) as a
大家看到了,最后一列rowNumber很有规律排列。这个对于一个想得到某个确定行数据的人来说实在是太惊喜了。比如现在我要取第8条数据,那么:
SELECT * FROM(SELECT *,ROW_NUMBER() OVER (ORDER BY plantId DESC) AS RowNumber FROM [bycommon].LogicEquipment) as a where a.rowNumber=8 ,ok轻松搞定。
还有大家有没有发现有了这个东西就可以进行对数据进行逐行处理了,类似于游标,写个sql看看。
SELECT * into #temp FROM(SELECT *,ROW_NUMBER() OVER (ORDER BY plantId DESC) AS RowNumber FROM [bycommon].LogicEquipment) as a
首先将数据写入一个临时表temp。现在我要做的是把companyId变为原来的二倍。
declare @i int,@maxId int,@id int
select @maxId=max(rowNumber) from #temp
set @i=1
while @i<=@maxId
begin
select @id=id from #temp where rowNumber=@i
update bycommon.logicEquipment set companyId=companyId*2 where id=@id
set @i=@i+1
end
select @maxId=max(rowNumber) from #temp
set @i=1
while @i<=@maxId
begin
select @id=id from #temp where rowNumber=@i
update bycommon.logicEquipment set companyId=companyId*2 where id=@id
set @i=@i+1
end