針對查詢「OpenDataSource」依關聯性排序顯示文章。依日期排序 顯示所有文章
針對查詢「OpenDataSource」依關聯性排序顯示文章。依日期排序 顯示所有文章

OpenDataSource 使用技巧及延伸

之前,曾經寫下 OpenDataSource 的用法;這方法一般來說,是夠使用了。
http://pertonchang.blogspot.com/search?q=OpenDataSource+

不過,當你使用的特殊字元來當密碼的一部份內容時,可能就會有問題。
==> 會抓不到資料.

再看下 OpenDataSource 的語法
SELECT   *
FROM OPENDATASOURCE(
     'SQLOLEDB',
     'Data Source=ServerName;User ID=MyUID;Password=MyPass'
          ).Northwind.dbo.Categories

記得用雙引號(")將特殊字元括住
SELECT   *
FROM OPENDATASOURCE(
     'SQLOLEDB',
     'Data Source=ServerName;User ID=MyUID;Password= "MyPass"'
          ).Northwind.dbo.Categories

另外,再介紹一個 Linked Server 的用法
如果你的環境有在 SQL Server ,Security / Linked Servers 中設定,例如:LOCAL
image
image
image

跨資料庫抓資料的語法,就變成了

SELECT   *
FROM LOCAL
.Northwind.dbo.Categories

如何引入外圍資料庫資料,來新增記錄?

image

新增記錄的 SQL 指令語法:
INSERT target_table
SELECT 'SELECT', authors.au_id, authors.au_lname, SUM(titles.price * sales.qty)
FROM authors
INNER JOIN titleauthor ON authors.au_id = titleauthor.au_id
INNER JOIN titles ON titleauthor.title_id = titles.title_id
INNER JOIN sales ON titles.title_id = sales.title_id
WHERE authors.au_id LIKE '8%'
GROUP BY authors.au_id, authors.au_lname

當資料來源與增建記錄的資料表,是不同資料庫時,
就需要用 OpenDataSource() 來開啟外圍資料庫的資料表。

用法如上所述。

 

Examples

This example accesses data from a table on another instance of SQL Server.

SELECT   *
FROM OPENDATASOURCE(
'SQLOLEDB',
'Data Source=ServerName;User ID=MyUID;Password=MyPass'
).Northwind.dbo.Categories


This is an example of a query against an Excel spreadsheet through the OLE DB provider for Jet.



SELECT * 
FROM OpenDataSource( 'Microsoft.Jet.OLEDB.4.0',
'Data Source="c:\Finance\account.xls";User ID=Admin;Password=;Extended properties=Excel 5.0')...xactions