sql-server 基礎: sql
一、查看sqlserver的數據表ide
SELECT name,crdate FROM SysObjects Where XType='U' order by crdate descsqlserver
查看數據表的字段優化
SELECT A.name AS table_name,B.name AS column_name,C.value AS column_description
FROM sys.tables A INNER JOIN sys.columns B
ON B.object_id = A.object_id LEFT JOIN sys.extended_properties C
ON C.major_id = B.object_id AND C.minor_id = B.column_id
WHERE A.name = '查詢表名'spa
二、編輯表字段code
添加字段: alter table table_name[表名] add field_name[添加字段名] type[字段類型] not nullserver
刪除字段: alter table table_name[表名] drop column field_name[字段名]blog
修改字段: alter table table_name[表名] alter column field_name[字段名] type[字段類型] not nullip
三、io
查詢表的約束:exec sp_helpconstraint [表名]
添加約束:alter table [表名] add constraint [約束名稱] [增長約束類型]
刪除約束關係:alter table [表名] drop constraint [約束名稱]
sql-server 優化相關:
一、查詢sql語句執行的耗時和IO消耗
set statistics io on
set statistics time on
-- 要執行的sql語句
set statistics io off
set statistics tine off
二、鏈接查詢優化
1 select a.*,b.name from 2 S_Linkup a left join u_union b on b.union_id = a.union_id 3 where a.CardID = 10 and a.union_id <> (select union_id from S_Card inner join u_union on S_Card.UserID=u_union.UserID where S_Card.CardID = 10)
能夠優化爲
1 select a.*, b.name from S_Linkup a, u_union b, S_Card c 2 where a.CardID = 10 and a.union_id = b.union_id and a.CardID = c.CardID and b.UserID <> c.UserID
3. 行轉列實例 : PIVOT
go -- ========================== -- 銷售季度表,ByYuanbo -- ========================== -- drop table SalesByQuarter create table SalesByQuarter ( year int, -- 年份 quarter char(2), -- 季度 amount money -- 總額 ); go -- 0一、插入數據 set nocount on declare @index int declare @q int set @index = 0 declare @year int while (@index < 30) begin set @year = 2005 + (@index % 4) set @q = (CasT((RAND() * 500) as int) % 4) + 1 insert into SalesByQuarter values(@year, 'Q' + CasT(@q as char(1)), RAND() * 10000.00) set @index = @index + 1 end; go -- 0二、查詢 select * from SalesByQuarter; go -- 0三、傳統 CASE 方法 select year as 年份 ,sum(case when quarter = 'Q1' then amount else 0 end) 一季度 ,sum(case when quarter = 'Q2' then amount else 0 end) 二季度 ,sum(case when quarter = 'Q3' then amount else 0 end) 三季度 ,sum(case when quarter = 'Q4' then amount else 0 end) 四季度 from SalesByQuarter group by year order by year desc; go -- 0四、PIVOT 方法 select year as 年份, Q1 as 一季度, Q2 as 二季度, Q3 as 三季度, Q4 as 四季度 from SalesByQuarter PIVOT(SUM (amount) FOR quarter IN (Q1, Q2, Q3, Q4) )P order by year desc; 示例腳本源