sql update小結

之前update用的很多,但都是簡單的單表操做,沒有在乎,最近查閱多表關聯更新及更新top n,發現update還真靈活,記錄以下(在mssqlserver2008r2下測試經過):sql

1單表操做 sqlserver

update table1 set col1=val[,col2=val2...]測試

[where 條件表達式] server

2多表關聯操做it

1)update 表名 set 列名 from 表1,表2 where 條件,此法源表(table1)不能用as別名,長表名很麻煩,以下:table

update table1 set col1=table2.col1date

from table2  where table1.pkey=table2.pkeyselect

2)使用別名表更新,簡潔!查詢

update t1 set col1=t2.col1top

from table1 t1,table2 t2  where t1.pkey=t2.pkey

3)更新來自查詢表

update t1 set col1=val

from (select * from table1 [where 條件表達式] )t1

應用:更新前n條

update t1 set col1=val

from (select top 10 * from table1 [where 條件表達式] order by 列n )t1

另外,查詢能夠是本庫中的表,也能夠是外庫表,如dblink鏈接的表或openrowset等

4)使用cte

;with t as(select * from table1  [where 條件表達式])

update t set  col1=val

相關文章
相關標籤/搜索