原文:常用SQL收藏

MSSQL Split表字段

--拆分字符串之后匹配结果集合
CREATE FUNCTION [dbo].[fnSplit](
@sInputList VARCHAR(8000) -- List of delimited items
, @sDelimiter VARCHAR(8000) = ',' -- delimiter that separates items
) RETURNS @List TABLE (item VARCHAR(8000)) BEGIN
DECLARE @sItem VARCHAR(8000)
WHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0
BEGIN
SELECT
@sItem=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX(@sDelimiter,@sInputList,0)-1))),
@sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX(@sDelimiter,@sInputList,0)+LEN(@sDelimiter),LEN(@sInputList)))) IF LEN(@sItem) > 0
INSERT INTO @List SELECT @sItem
END IF LEN(@sInputList) > 0
INSERT INTO @List SELECT @sInputList -- Put the last item in
RETURN
END ----------------------使用方法
if object_id('tempdb..#Tmp') is not null
drop table #Tmp
create table #Tmp --创建临时表#Tmp
(
ID VARCHAR(100)
); DECLARE @iid VARCHAR(100)
declare @name varchar(500)
declare cursor1 cursor for --定义游标cursor1
select iid,props from Iteminfos --使用游标的对象
open cursor1 --打开游标 fetch next from cursor1 into @iid,@name --将游标向下移1行,获取的数据放入之前定义的变量@iid,@name中 while @@fetch_status=0 --判断是否成功获取数据
begin
IF((select COUNT(*) FROM fnSplit(@name, ';') WHERE item = '20000:20090')>0)
INSERT INTO #Tmp (ID) VALUES (@iid)
fetch next from cursor1 into @iid,@name --将游标向下移1行
end close cursor1 --关闭游标
deallocate cursor1 SELECT * FROM dbo.Iteminfos WHERE iid IN( SELECT ID FROM #Tmp)

查询节点的函数

create table tb(id varchar(3) , pid varchar(3) , name varchar(10))
insert into tb values('001' , null , '广东省')
insert into tb values('002' , '001' , '广州市')
insert into tb values('003' , '001' , '深圳市')
insert into tb values('004' , '002' , '天河区')
insert into tb values('005' , '003' , '罗湖区')
insert into tb values('006' , '003' , '福田区')
insert into tb values('007' , '003' , '宝安区')
insert into tb values('008' , '007' , '西乡镇')
insert into tb values('009' , '007' , '龙华镇')
insert into tb values('010' , '007' , '松岗镇')
go
-------------创建方法
create function f_cid(@ID varchar(3)) returns @t_level table(id varchar(3) , level int)
as
begin
declare @level int
set @level = 1
insert into @t_level select @id , @level
while @@ROWCOUNT > 0
begin
set @level = @level + 1
insert into @t_level select a.id , @level
from tb a , @t_Level b
where a.pid = b.id and b.level = @level - 1
end
return
END
GO
--------------使用方法
select a.* from tb a , f_cid('001') b where a.id = b.id order by a.id
--------------调用函数查询(广州市)及其所有子节点
select a.* from tb a , f_cid('002') b where a.id = b.id order by a.id

Exists,Datediff,Newid,

---两张关联表,删除主表中已经在副表中没有的信息
delete from table1 where not exists ( select * from table2 where table1.field1=table2.field1 ) ---日程安排提前五分钟提醒
SQL: select * from 日程安排 where datediff('minute',f开始时间,getdate())>5 ---随机取出10条数据
select top 10 * from tablename order by newid() -- 类似有 month day year
select * from table1 where convert(varchar,date,120) like '2006-04-01%'
--datediff
select * from table1 where datediff(day,time,'2006-4-1')=0

删除重复值

--1、查找表中多余的重复记录,重复记录是根据单个字段(peopleId)来判断
select * from people
where peopleId in (select peopleId from people group by peopleId having count(peopleId) > 1) --2、删除表中多余的重复记录,重复记录是根据单个字段(peopleId)来判断,只留有rowid最小的记录
delete from people
where peopleId in (select peopleId from people group by peopleId having count(peopleId) > 1)
and rowid not in (select min(rowid) from people group by peopleId having count(peopleId )>1) --3、查找表中多余的重复记录(多个字段)
select * from vitae a
where (a.peopleId,a.seq) in (select peopleId,seq from vitae group by peopleId,seq having count(*) > 1) --4、删除表中多余的重复记录(多个字段),只留有rowid最小的记录
delete from vitae a
where (a.peopleId,a.seq) in (select peopleId,seq from vitae group by peopleId,seq having count(*) > 1)
and rowid not in (select min(rowid) from vitae group by peopleId,seq having count(*)>1) --5、查找表中多余的重复记录(多个字段),不包含rowid最小的记录
select * from vitae a
where (a.peopleId,a.seq) in (select peopleId,seq from vitae group by peopleId,seq having count(*) > 1)
and rowid not in (select min(rowid) from vitae group by peopleId,seq having count(*)>1) --经典尝试 删除重复值 declare @table table (id int,name nvarchar(10))
insert into @table select 1,'aa'
union all select 1,'aa'
union all select 2,'bb'
union all select 3,'bb'
union all select 4,'cc'
union all select 1,'aa'
union all select 4,'cc' delete a
from (
select id,name,rn = row_number() over (partition by id,name order by id) from @table
) a where rn > 1 select * from @table id name
----------- ----------
1 aa
2 bb
3 bb
4 cc (4 row(s) affected)

常用日期转换参数

select CONVERT(varchar, getdate(), 120 )
--结果
2004-09-12 11:06:08
select replace(replace(replace(CONVERT(varchar, getdate(), 120 ),'-',''),' ',''),':','')
--结果
20040912110608
select CONVERT(varchar(12) , getdate(), 111 )
--结果
2004/09/12
select CONVERT(varchar(12) , getdate(), 112 )
--结果
20040912
select CONVERT(varchar(12) , getdate(), 102 )
--结果
2004.09.12

行转列

create table tb(姓名varchar(10) , 课程varchar(10) , 分数int)
insert into tb values('张三' , '语文' , 74)
insert into tb values('张三' , '数学' , 83)
insert into tb values('张三' , '物理' , 93)
insert into tb values('李四' , '语文' , 74)
insert into tb values('李四' , '数学' , 84)
insert into tb values('李四' , '物理' , 94)
go select 姓名 as 姓名,
max(case 课程 when '语文' then 分数 else 0 end) 语文,
max(case 课程 when '数学' then 分数 else 0 end) 数学,
max(case 课程 when '物理' then 分数 else 0 end) 物理,
cast(avg(分数*1.0) as decimal(18,2)) 平均分,
sum(分数) 总分
from tb
group by 姓名 --SQL SERVER 2000 动态SQL。
declare @sql varchar(8000)
set @sql = 'select 姓名 '
select @sql = @sql + ' , max(case 课程 when ''' + 课程 + ''' then 分数 else 0 end) [' + 课程 + ']'
from (select distinct 课程 from tb) as a
set @sql = @sql + ' , cast(avg(分数*1.0) as decimal(18,2)) 平均分, sum(分数) 总分 from tb group by 姓名'
exec(@sql) --姓名 数学 物理 语文 平均分 总分
--李四 84 94 74 84.00 252
--张三 83 93 74 83.33 250

通过子节点ID得到所有父节点

ALTER function [dbo].[f_cid](@id int)
returns @t table(id int,[name] varchar(30),parentid int,lev int)
as
begin
declare @lev int
set @lev=1
insert into @t SELECT cid,name,parent_cid,@lev from TB_ItemCats where cid=@id
while(@@rowcount>0)
begin
set @lev=@lev+1
insert into @t select a.cid,a.name,a.parent_cid,@lev from TB_ItemCats a,@t b
where a.cid=b.parentid and b.lev=@lev-1 AND a.cid NOT IN (select b.id from @t)
end
return
END

123

3232

123

3232

123

3232

123

3232

123

3232

123

3232

123

3232

123

3232

123

3232

123

3232

123

3232

常用SQL收藏的更多相关文章

  1. Mysql 常用 SQL 语句集锦

    Mysql 常用 SQL 语句集锦 基础篇 //查询时间,友好提示 $sql = "select date_format(create_time, '%Y-%m-%d') as day fr ...

  2. oracle(sql)基础篇系列(一)——基础select语句、常用sql函数、组函数、分组函数

        花点时间整理下sql基础,温故而知新.文章的demo来自oracle自带的dept,emp,salgrade三张表.解锁scott用户,使用scott用户登录就可以看到自带的表. #使用ora ...

  3. 常用SQL[ORACLE]

        1.常用系统函数 2.常用sql语句 3.一些定义和关键字 4.需要注意点   1.常用系统函数 ↑ --decode decode(column,if_value,value,elseif_ ...

  4. Oracle常用SQL查询(2)

    三.查看数据库的SQL 1 .查看表空间的名称及大小 select  t.tablespace_name,  round ( sum (bytes / ( 1024 * 1024 )), 0 ) ts ...

  5. Oracle常用SQL查询

    一.ORACLE的启动和关闭 1.在单机环境下要想启动或关闭oracle系统必须首先切换到oracle用户,如下: su - oracle a.启动Oracle系统 oracle>svrmgrl ...

  6. Mysql 常用 SQL 语句集锦 转载(https://gold.xitu.io/post/584e7b298d6d81005456eb53)

    Mysql 常用 SQL 语句集锦 基础篇 //查询时间,友好提示 $sql = "select date_format(create_time, '%Y-%m-%d') as day fr ...

  7. 50个常用SQL语句

    50个常用SQL语句 Student(S#,Sname,Sage,Ssex) 学生表  S#学号,主键 Course(C#,Cname,T#) 课程表          C#课程号,主键 SC(S#, ...

  8. 测试常用SQL注入语句大全

    转载自Cracer,标题:<渗透常用SQL注入语句大全>,链接http://www.xxxx.com/?p=2226 1.判断有无注入点 整形参数判断 1.直接加' 2.and 1=1 3 ...

  9. oracle sqlplus及常用sql语句

    常用sql语句 有需求才有动力 http://blog.csdn.net/yitian20000/article/details/6256716 常用sql语句 创建表空间:create tables ...

随机推荐

  1. [错误解决]pandas DataFrame中经常出现SettingWithCopyWarning

    先从原dataframe取出一个子dataframe,然后再对其中的元素赋值,例如 s = d[d['col_1'] == 0] s.loc[:, 'col_2'] = 1 就会出现报错: Setti ...

  2. 软件工程概论课堂测试一————添加新课程(web)

    设计思想 三个文件Class_add.java  add.jsp  addInput.jsp Class_add.java : 内封装方法:连接数据库.向数据库添加课程信息.判断非合理的输入情况.判断 ...

  3. 华为手机怎么安装Google

    华为手机怎么安装google 新买了个华为荣耀九,结果安装Google Play提示gms core 步骤一 gms 安装器.应用市场已经下架了  地址:链接: 点击打开链接 密码: m63j 步骤二 ...

  4. GCD 开发详情

    目录 一.简介 二.dispatch Queue - 队列 三.dispatch Groups - 组 四.dispatch Semaphores - 信号量 五.dispatch Barriers ...

  5. 纪中集训总结 && 新学期目标

    于是紧接着又发了第二篇. 关于这次去完纪中以后的感想,写完后总觉得少了些什么,因此就发一篇小目标集合来凑数补充一下吧. Part I:图论 这方面我去之前就是很有自信,事实证明像基础的最短路.生成树什 ...

  6. ccpc 网络赛 hdu 6155

    # ccpc 网络赛 hdu 6155(矩阵乘法 + 线段树) 题意: 给出 01 串,要么询问某个区间内不同的 01 子序列数量,要么把区间翻转. 叉姐的题解: 先考虑怎么算 \(s_1, s_2, ...

  7. nginx配置C compiler cc is not found

    1.需求 linux安装个编译器 参考资料:http://blog.csdn.net/testcs_dn/article/details/51461750

  8. Oracle 对字符串去重函数

    CREATE OR REPLACE FUNCTION ZZMES."REMOVESAMESTR" (oldStr varchar2, sign varchar2) return v ...

  9. CSS 清除浮动的4种方法

    此为未清除浮动源代码,运行代码无法查看到父级元素浅黄色背景.<style type=”text/css”> <!– *{margin:0;padding:0;} body{font: ...

  10. Hibernate中的延迟加载及fetch

    Hibernate中的延迟加载 1.类级别的查询策略: lazy  :  true(默认值) false(立即加载) 2.多对一关联的查询策略: lazy:  proxy(默认值) no-proxy ...