SQL Server效能常用語句

2021-09-06 16:46:56 字數 2454 閱讀 2683

檢視各表的資料行數

select

o.name, i. rows

from sysobjects o, sysindexes i

where o.id = i.id and o.xtype = '

u' and i.indid < 2

order by o.name;

計算資料庫中各個表每行記錄所占用空間

--select *from employees as e;

create table #tablespaceinfo

(nameinfo varchar(

50) ,

rowsinfo bigint ,

reserved varchar(

20) ,

datainfo varchar(

20) ,

index_size varchar(

20) ,

unused varchar(20)

) declare @tablename varchar(

255);

declare info_cursor cursor

for select '[

' + [name] + ']'

from sys.tables

where type = 'u'

;

open info_cursor

fetch next from info_cursor into @tablename

while @@fetch_status = 0

begin

insert into #tablespaceinfo

exec sp_spaceused @tablename

fetch next from info_cursor

into @tablename

end

close info_cursor

deallocate info_cursor

--建立臨時表

create table [#tmptb]

(tablename varchar(

50) ,

datainfo bigint ,

rowsinfo bigint ,

spaceperrow as ( case rowsinfo

when

0 then 0

else cast(datainfo as

decimal(18,2))/cast(rowsinfo as decimal(18,2

)) end ) persisted

)--插入資料到臨時表

insert into [#tmptb]

( [tablename] ,

[datainfo] ,

[rowsinfo]

)select [nameinfo] ,

cast(replace([datainfo], 'kb

', '') as bigint) as '

datainfo',

[rowsinfo]

from #tablespaceinfo

order by cast(replace(reserved, 'kb

', ''

) as int) desc

--彙總記錄

select [tbspinfo].*,

[tmptb].[spaceperrow] as

'每行記錄大概占用空間(kb)

'from [#tablespaceinfo] as tbspinfo ,

[#tmptb] as tmptb

where [tbspinfo].[nameinfo] =[tmptb].[tablename]

order by cast(replace([tbspinfo].[reserved], 'kb

', ''

) as int) desc

drop table [#tablespaceinfo]

drop table [#tmptb]

獲取sql語句執行時

declare

@adatetime

declare

@bdatetime

select@a=

getdate

()exec sp_tables; --

檢視表select@b=

sqlserver常用語句

刪除主鍵 alter table 表名 drop constraint 主鍵名 新增主鍵 alter table 表名 add constraint 主鍵名 primary key 欄位名1,欄位名2 新增非聚集索引的主鍵 alter table 表名 add constraint 主鍵名 prim...

SQLSERVER常用語句

dbcc cleantable db name table name alter table drop column語句刪除可變長度列或text dbcc dbreindex 重建指定資料庫的乙個或多個索引 dbcc indexdefrag 對錶或檢視上的索引和非聚集索引進行碎片整理 dbcc pi...

SQL Server 常用語句合集

1 對資料進行排序 select row number over order by a.articleid desc as rn row number 計算一行在結果集中的行號,可以當作是唯一的排名。rank over order by a.typeid desc rank 和dense rank ...