sql-server 基础:
1、查看sqlserver的数据表
SELECT name,crdate FROM SysObjects Where XType='U' order by crdate desc
查看数据表的字段
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 = '查询表名'
2、编辑表字段
添加字段: alter table table_name[表名] add field_name[添加字段名] type[字段类型] not null
删除字段: alter table table_name[表名] drop column field_name[字段名]
修改字段: alter table table_name[表名] alter column field_name[字段名] type[字段类型] not null
3、
查询表的约束:exec sp_helpconstraint [表名]
添加约束:alter table [表名] add constraint [约束名称] [增加约束类型]
删除约束关系:alter table [表名] drop constraint [约束名称]
sql-server 优化相关:
1、查询sql语句执行的耗时和IO消耗
set statistics io on
set statistics time on
-- 要执行的sql语句
set statistics io off
set statistics tine off
2、连接查询优化
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 -- 01、插入数据 set nocount on declare @index int declare @q int set @index = 0 declare @year int while (@index < 30) beginset @year = 2005 + (@index % 4)set @q = (CasT((RAND() * 500) as int) % 4) + 1insert into SalesByQuarter values(@year, 'Q' + CasT(@q as char(1)), RAND() * 10000.00)set @index = @index + 1 end; go -- 02、查询 select * from SalesByQuarter; go -- 03、传统 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 -- 04、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;示例脚本源