记录执行时间:
SET STATISTICS TIME ON
SELECT * FROM SYSOBJECTS -->你的查询
SET STATISTICS TIME OFF
(1)sql语句执行顺序:https://docs.microsoft.com/en-us/previous-versions/sql/sql-server-2008/ms189499(v=sql.100)
1、FROM
2、ON
3、JOIN
4、WHERE
5、GROUP BY
6、WITH CUBE or WITH ROLLUP
7、HAVING
8、SELECT
9、DISTINCT
10、ORDER BY
11、TOP
(也就是说, 先进行on的过滤, 而后才进行join, 这样就避免了两个大表产生全部数据的笛卡尔积的庞大数据. )
(2)分组查询group by...having
对group by分组后的数据进行过滤在分组查询中,查询的列名必须出现在group by后或者在聚合函数中
--查询平均工资大于两千块钱的部门
select department_id,avg(wages)
from employee
where department_id is not null
group by department_id
having avg(wages)>2000
(3)print
declare @msg nvarchar(max)
set @msg='abcdef'
print @msg
消息框中打印出:abcdef
(4)case when then
写法一:
select id,username,role,
case role
when 1 then '普通用户'
when 2 then '发布员'
else '管理员'
end as '角色'
from data
写法二:
select id,username,role,
case
when role=1 then '普通用户'
when role=2 then '发布员'
else '管理员'
end as '角色'
from couser
赋值时的写法:
set @orderby=
case @orderid
when 1 then ' posted desc,truename asc'
when 2 then ' geted desc,truename asc'
when 3 then ' readed desc,truename asc'
else ' posted desc,truename asc'
end
where中使用case when:
select * from datatable where (case colid when 0 then 1 end) = 1
(5)动态执行SQL语句
sp_executesql
字符串前面加大写N表示,N'string' 表示string是个Unicode字符串。
例如:exec sp_executesql @sql,N'@schoolid int,@isbiye int,@step int,@ji int,@jie int',@schoolid,@isbiye,@step,@ji,@jie
exec
exec (N'select * from table where name like ''%@keyword%''')
注:单引号的转义方式是替换成两个单引号''
(6)select返回某字段重组的字符串FOR XML PATH('')
select top 5 cast(id as nvarchar(255))+',' from datatable where schoolid=1 FOR XML PATH('')
返回:49,48,47,46,45
详细可查看这篇文章:http://www.cnblogs.com/doubleliang/archive/2011/07/06/2098775.html
(7)将结果集整体插入另一张表对应字段
前提是字段类型和数量都符合
语法:insert into A(field11,field22,field33) select field1,field2,field3 from B where id in(...)
这句实现将B提取出来的结果集,插入到表A对应字段