利用SQL語句重置資料庫中所有表的標識列 自增量

2022-04-08 06:05:41 字數 1744 閱讀 3730

可以應用於2種場景:

1.清空所有表中的資料,資料清空後,最好是能夠讓表中的標識列從1開始記數,所以要重置標識列的當前值。

2.用複製的方式,發布訂閱同步資料之後,訂閱端的資料不會自動增長,比如自增id該9527了,但如果中間有跳過的id,會自動填充缺失的路過的id,該執行如下**,即可從應該的9527開始增長。

declare

@tablename

varchar(50

) declare

@sql

varchar(1000

)declare cur cursor

forselect name from

sys.tables

open

curfetch

next

from cur into

@tablename

while

@@fetch_status=0

begin

set@sql='

if (select count(1) from '+

@tablename+'

)<=0 and exists(select * from sys.columns where is_identity=1 and object_id=object_id(

'''+

@tablename

+'''

))begin

--dbcc checkident('+

@tablename+'

,reseed,1)

dbcc checkident('+

@tablename+'

,reseed)

end'

exec (@sql

)fetch

next

from cur into

@tablename

endclose

curdeallocate cur

測試過沒有問題的

--

已經測試沒有問題的生成有標識列(自增id)的表名

declare

@tablename

varchar(50

) declare

@sql

varchar(1000

)declare

@objiecid

intdeclare cur cursor

forselect

object_id

from sys.columns where is_identity=

1open

curfetch

next

from cur into

@objiecid

while

@@fetch_status=0

begin

select

@tablename

=name from sys.tables where

object_id

=@objiecid

--print @tablename

print

'dbcc checkident(

'''+

@tablename

+'''

,reseed)

'fetch

next

from cur into

@objiecid

endclose

curdeallocate cur

利用SQL語句查詢資料庫中所有表

oracle select from all tables 系統裡有許可權的表 select from dba tables 系統表 select from user tables 當前使用者下的表 sql server 1,利用sysobjects系統表 在這個表中,在資料庫中建立的每個物件 例如...

SQL語句 查詢資料庫中所有非系統表的資訊

select case when a.colorder 1 then d.name else end 表名,a.colorder 字段序號,a.name 欄位名,case when columnproperty a.id,a.name,isidentity 1 then else end 標識,ca...

sql查詢資料庫中所有表名 續

讀取庫中的所有表名 select name from sysobjects where xtype u 讀取指定表的所有列名 select name from syscolumns where id select max id from sysobjects where xtype u and na...