幾個有用的Sql語句(在Sql Server2000的查詢分析器裡測試通過)

來源:互聯網
上載者:User
1、例如:有兩個表A(欄位1,欄位2,欄位3)、B(欄位2,欄位3),其中儲存資料如下所示
表A
欄位1 欄位2 欄位3
1 <Null> 地段內容1
1 <Null> 地段內容1
2 <Null> 地段內容2
2 <Null>

地段內容2

3 <Null> 地段內容3
4 <Null> 地段內容4
5 <Null> 地段內容5
5 <Null> 地段內容5
5 <Null> 地段內容5
6 <Null> 地段內容6
7 <Null> 地段內容7
8 <Null> 地段內容8
8 <Null> 地段內容8
8 <Null> 地段內容8
8 <Null> 地段內容8

表B

欄位2 欄位3
wdz1 地段內容1
wdz2 地段內容3
wdz3 地段內容5
wdz4 地段內容6
wdz5 地段內容7
wdz6 地段內容8

使用下面的Sql語句(可以達到將表A中欄位3與表B中欄位3相同的資料欄位2填充到表A中的欄位2)
update 表1 set 欄位1 = (select 欄位1 from 表2 where 表1.欄位3=表2.欄位3)
結果如下表所示
表A結果

欄位1 欄位2 欄位3
1 wdz1 地段內容1
1 wdz1 地段內容1
2 <Null> 地段內容2
2 <Null>

地段內容2

3 wdz2 地段內容3
4 <Null> 地段內容4
5 wdz3 地段內容5
5 wdz3 地段內容5
5 wdz3 地段內容5
6 wdz4 地段內容6
7 wdz5 地段內容7
8 wdz6 地段內容8
8 wdz6 地段內容8
8 wdz6 地段內容8
8 wdz6 地段內容8

下面是本條Sql語句的網友意見
一、“江千帆”
update 表1 set 欄位1 = (select 欄位1 from 表2 where 表1.欄位3=表2.欄位3)
的效率很低,如果有X條記錄,會導致子查詢執行X次.
如果我們這樣寫,就可以充分利用索引(如果兩表在欄位3上面都建立了索引),並且避免不必要的多次執行。
update 表1 set 表1.欄位2 =表2.欄位2 from 表1 inner join 表2 on 表1.欄位3=表2.欄位3

網友意見歸納結束。

2、例如:如第1點中的表A相同,需要查詢出表A的重複資料的Sql語句如下
select 欄位1 from 表A group by 欄位1 having count(欄位3) > 1
查詢結果如下
表A查詢結果

欄位1
1
2
5
8

3、例如:需要在Sql Server2000中查詢處某固定實體路徑的X1.dbf檔案,使用的Sql語句如下(必須先安裝VF驅動才能使用此Sql語句)
select * from OpenDataSource('VFPOLEDB.1','User ID=;DSN=;Collating Sequence=MACHINE;Data Source=C:\dbfFiles\X1.dbf;Password=;Cache Authentication=False;Mask Password=False;Mode=Share Deny None;Extended Properties=;Encrypt Password=False')...X1
註:其他的非VF資料庫檔案的查詢類似,只需要設定OpenDataSource中的參數即可。參數說明為OpenDataSource(資料來源驅動名,資料來源連接字串)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.