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

相关文章
相关标签/搜索