SQL Server 常用集锦

1、设置表结构某列的值,为固定排序后的行号值的SQL语句示例:

update AppStations  set [index]=t1.rowId
 from
(select stationNum,stationName,row_number() over(order by stationNum) as rowId
from AppStations)  t1 where t1.stationNum=AppStations.stationNum

2、查询表在数据库中,其他表中的外键

select * from sys.foreign_keys 
where referenced_object_id=object_id('表名称') order by 1

3、重置表自动增长列为0

   3.1、使用DBCC控制台命令   

dbcc checkident(表名,RESEED,0)
   3.2、truncate table 也可将当前标识值清零,但当有外键等约束时,无法truncate表
truncate table 表名
4、树形查询、删除
  with cte as
(
select * from Resource where id='C3940DA6-CAF7-498A-86C0-4D8090B9C112'
union all
select a.* from Resource a  inner join  cte b on ( a.ParentID=b.id)    
)
 
select * from cte
delete Resource where ID in(select ID from  cte )

你可能感兴趣的:(SQL,Server,小记)