顯示具有 MSSQL 標籤的文章。 顯示所有文章
顯示具有 MSSQL 標籤的文章。 顯示所有文章

2009年11月27日 星期五

存取遠端資料庫伺服器的方法

三種方法可擇一使用

1. 使用SQL Server Enterprise Manager工具


選擇某一SQL Server --> 安全性 --> 連結伺服器 --> 新增連結伺服器  在【一般】頁籤中的連結的伺服器欄位中輸入欲連結伺服器的網路名稱全名。
顯示畫面如下:



在【安全性】頁籤中,選擇【使用下列安全性條件進行連線】輸入帳號及密碼。
顯示畫面如下:



2. 在QUERY ANALYZER中輸入


EXEC sp_addlinkedserver ‘xxx.xxx.xxx.xxx’,N’SQLServer的名稱’

EXEC sp_addlinkedsrvlogin ‘xxx.xxx.xxx.xxx’,’false’,NULL,’使用者帳號’,’密碼’

註: 其中紅色字體的N就直接輸入N 代表後面的字是Unicode

3. 直接在SQL指令中加入遠端伺服器連結資訊


以下範例查詢cydc.cyu.edu.tw資料庫伺服器中person資料庫的dbo所擁有的baperson資料表

select *


from opendatasource('sqloledb','data source=cydc.cyu.edu.tw;user id=帳號;password=密碼').person.dbo.baperson

4. 不同使用方法的差異:


若使用上述1及2的方式只需事先於該SQL Server中執行一次註冊動作,往後執行SQL 指令時可直接使用以下的方法連結到遠端資料庫:

select *


from [cydc.cyu.edu.tw].person.dbo.baperson

若使用第3種方法的話,則只需於每次執行SQL 指令時加入相關的連結資訊即可,不需事先執行1及2的前置動作。

2009年11月26日 星期四

善用規則運算式(Regular Expressions)

如果你非要用字串串連的方式建立 SQL 查詢的話,你就要自己篩選輸入資料。以下範例使用規則運算式過濾特殊字元及部份關鍵字:

string inputString = txtSearch.Text;inputString = Regex.Replace(inputString, @"\b(exec(ute)?|select|update|insert|delete|drop|create)\b|[;']|(-{2})|(/\*.*\*/)", string.Empty, RegexOptions.IgnoreCase);

請注意,如果是使用 LIKE 來執行字串比較,即便是使用參數型命令,你仍需要逸出萬用字元:

Regex re = new Regex(@"(?[\[\%_])");inputString = re.Replace(inputString, "[${EscapeChar}]");

MSSQL 權限設定回復方法

declare @dbname nvarchar(200), @cmd2 nvarchar(2000)
declare c_db cursor for
select name from sysdatabases where dbid > 4
open c_db fetch next from c_db into @dbname
while @@fetch_status=0
begin
print @dbname
set @cmd2='use '+@dbname + ' ' +
'
declare @name nvarchar(200), @cmd nvarchar(200)
declare c_user cursor for
select name from sysusers where altuid is null and createdate > ''2001/1/1''


open c_user
fetch next from c_user into @name
while @@fetch_status=0
begin
print @name
exec sp_change_users_login ''Auto_Fix'', @name
fetch next from c_user into @name
end
close c_user
deallocate c_user
'
exec (@cmd2)
--print (@cmd2)
fetch next from c_db into @dbname
end
close c_db
deallocate c_db

--altuid is null (SQL Server 2008) §令 altuid = 0 (SQL Server 2000)
-- exec sp_change_users_login ''Update_One'',@name,@name (SQL Server 2008)
-- ''Auto_Fix'', @name (SQL Server 2000)

修改MSSQL 的連線逾時設定

SQL Server 本機用 Enterprise Manager 用 工具->選項->進階,加大逾時秒數。
或是用指令
USE master
GO
EXEC sp_configure 'remote query timeout', 1200
GO
RECONFIGURE
GO
1200 代表的是秒(SQL Server預設是 600 秒,),設為0表示永不逾時。