首页 > 代码库 > 常用SQL脚本记录一
常用SQL脚本记录一
20、SUM()和 列+ 统计结果时:如果列里有一行为null,SUM函数会忽略它;如果+,则结果集也为NULL了
19 SUBSTRING (expression,startIndex, endIndex)
SELECT SUBSTRING (‘Los Angeles‘,1, 3)
返回结果Los,默认索引从1开始
18 SQL分隔字符串函数返回一个table数据集
,拆成结果集
SELECT * FROM dbo.fn_split(‘A,B,CD,EFG,H‘,‘,‘)
Table里"-"列SET_006列拆分
SELECT T1.SET_003,T2.splitcolumn
FROM Table AS T1
OUTER APPLY(SELECT splitcolumn FROM dbo.split(T1.SET_006,‘-‘)) AS T2
WHERE T2.splitcolumn<>‘‘
CREATE FUNCTION [dbo].[fn_split]
(
输入字符串
@InputString NVARCHAR(MAX),
分隔符号
@Seprator NVARCHAR(10)
) RETURNS @tempTable TABLE ([value] NVARCHAR(200))
AS
BEGIN
DECLARE @index int
DECLARE @value NVARCHAR(200)
去除输入字符串前后的空格
SET @InputString = RTRIM(LTRIM(@InputString)) 分隔符号@Seprator在输入字符串@InputString中的开始位置
SET @index=CHARINDEX(@Seprator, @InputString)
WHILE @index>0
BEGIN
返回输入字符串(@InputString)左边开始指定个数(@index-1)的字符
SET @value=http://www.mamicode.com/LEFT(@InputString,@index-1)
插入数据
INSERT @tempTable VALUES(@value)
重新设置输入字符串 截取输入字符串从输入字符串@index+1处开始且长度为LEN(@InputString)-@index
SET @InputString = SUBSTRING(@InputString, @index+1, LEN(@InputString)-@index)
分隔符号@Seprator在输入字符串@InputString中的开始位置
SET @index=CHARINDEX(@Seprator, @InputString)
END
如果输入字符串不为空
IF(@InputString<>‘\‘)
BEGIN
INSERT @tempTable VALUES(@InputString)
END
RETURN
END
取一个userid对应多个roleid集合字符串
CREATE FUNCTION [dbo].[fn1GetRoleNane]
(
@userid INT
)
returns varchar(500)
AS
BEGIN
DECLARE @tmp VARCHAR(500)
SELECT @tmp=isnull(@tmp+‘,‘, )+RTRIM(LTRIM(r.roleName)) FROM UserAndRole ar, Role r WHERE r.RoleID=ar.roleID AND ar.userid=@userid
RETURN ISNULL(@tmp, )
END
17 强制将一个数据表的排序规则按照另一个表的排序规则,进行查询
UPDATE dbo.Table1
SET Col_167 = ISNULL(D.Col_120,0)
FROM dbo.Table1 AS M
LEFT JOIN dbo.MobileInfo AS B2 ON M.Col_047 = B2.M_User
COLLATE Chinese_PRC_CI_AS
16 Alter新增字段,及给默认值
ALTER table Table1 Add DD_031 nvarchar(50) not null default N
15 RIGHT 和LEFT 返回最右侧的n个字符的字符串str,或NULL如果任何参数是NULL。
补位: right(‘000000‘ + cast(isnull(MAX(InNO),0)+1 as nvarchar), 6)
15 CAST函数用于将某种数据类型的表达式显式转换为另一种数据类型
cast((ISNULL(Col_018,0)*ISNULL(JTAsRate,0)/100-isnull(Col_308,0)) as decimal(18,2))<>Col_305
14 case when 写法
SELECT [id] ,[name],[school],[score],
case
when score>=90 then ‘优秀‘
when score>=80 then ‘良好‘
when score>=70 then ‘一班‘
when score>=60 then ‘及格‘
else ‘不及格‘
end
from [Table_1]
13 while break流程控制语句
while (select avg([score]) from [Table_1] where id between 3 and 15)<85
begin
update [Table_1]
set score=score+5
if (select max(score) from [Table_1] where id between 3 and 15)>=100
break 跳出本层循环
continue 跳出本次循环
end
12 GOTO 流程控制语句的精简运用(可以从多个循环中直接跳出,而Break语句只可以跳出一个While循环。)
IF NOT EXISTS(SELECT 1 FROM #TR_LogisticsPH_LH WHERE UniqId=11)
BEGIN
GOTO GetRelust
END
GetRelust: SELECT * FROM #TR_LogisticsPH_LH
11 SQL SERVER 不区分大小写 -
用不上 UPPER() 和 LOWER(),
10 显示参数清单和其数据类型
EXEC sp_help Table1
9 通常使用NULLIF()函数可以防止除零错误。
select a/nullif(b,0)
8 DATEDIFF功能 返回两个日期之间的间隔。
语法 DATEDIFF ( date-part, date-expression-1, date-expression-2 )
date-part : year | quarter | month | week | day | hour | minute | second | millisecond
参数 date-part 指定要测量其间隔的日期部分。
date-expression-1 某一间隔的起始日期。从 date-expression-2 中减去该值,返回两个参数之间 date-parts 的天数。
AND Col_004>DATEADD(MONTH,-3,GETDATE()) 最近三个月内
7、脏读,
FROM Table1 AS YM WITH(READPAST)
WITH(NOLOCK) 可能把没有提交事务的数据也显示出来.
WITH(READPAST) 会把被锁住的行不显示出来
6 创建非聚集索
CREATE UNIQUE CLUSTERED INDEX IX_Table1 ON Table1(Col_113)
with schemabinding
AS
select Userinfo *,UserClass * from Userinfo inner join UserClass on uid=cid
注意,表的表达式必须使用两段式 dbo.mytable 否则会报
"名称必须由两部分构成,并且对象不能引用自身。"
而且必须先建一个唯一的聚集所引,否则也是不能进行接下为的所引建立的。
也不是说必须要先用一个唯一的聚集所引才行哦
如果大家想正常使用视图所引的话就保证你的表中在建完视图后有一个列是唯一的哦
5 临时表里判断是否存在行,修改其值
select t1.col_001 ,t1.col_002 ,t1.sys_guid,t2.col_049,t2.col_005,t2.col_010 ,T2.col_011 ,
t2.col_014,t2.col_013,CAST((isnull(t2.col_036,0)-4.18) as decimal(18,2)) * t2.col_010 as oliCharge
INTO #TEMP
from
Table1 t1 LEFT JOIN Table2 t2 on t1.col_001=t2.col_006
UPDATE temp SET temp.col_011= CAST(ISNULL(temp.col_010,0) AS DECIMAL(18,2)) *4.18
FROM #TEMP temp
WHERE EXISTS(SELECT 1 FROM Table1 WHERE col_001=temp.col_005)
DROP TABLE #TEMP
4 查找重复值
select top 10 * from Table1 a where exists (select Col_003 from Table1 b group by col_003 having count(Col_003)>2 and a.col_003=b.Col_003)
3 charindex判断 0,表示不存在
select * from Table1
where (( (CHARINDEX(N‘飞越‘,Col_043,1)=0 OR CHARINDEX(N‘飞越‘,Col_051,1)>0))
AND ISNULL(Col_113, ) <> AND Col_006<=2 AND Col_004=1
-2、NOT IN 另一种写法
select * from (values(‘13000452388‘,12),(‘13001215092‘,23),(‘13001557229‘,33)) dddd(phoneno,noa)
批量插入
insert into persons
(id_p, lastname , firstName, city )
values
(200,‘haha‘ , ‘deng‘ , ‘shenzhen‘),
(201,‘haha2‘ , ‘deng‘ , ‘GD‘),
(202,‘haha3‘ , ‘deng‘ , ‘Beijing‘);
/****** 简单说明(作者***:日期)**/
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = ‘‘) AND type in (N‘U‘))
DROP TABLE table
GO
CREATE TABLE table
(
UniqueID bigint primary key identity(1,1),
YDNo NVARCHAR(50),
YDSJ DATETIME,
ReadMan NVARCHAR(50),
ReadDepartment NVARCHAR(50),
ReadDate DATETIME,
PDANumber NVARCHAR(50),
sys_guid varchar(50) DEFAULT (replace(newid(),‘-‘, ))
)
声明表变量 -
declare @Detail table(ID int,Price float)
insert into @order(ID,Name) values(1,‘aa‘),(2,‘bb‘),(3,‘cc‘)
1、统计每月,每日数据
每月
select year(ordertime) 年,
month(ordertime) 月,
sum(Total) 销售合计
from 订单表
group by year(ordertime),
month(ordertime
每日
select year(ordertime) 年,
month(ordertime) 月,
day(ordertime) 日,
sum(Total) 销售合计
from 订单表
group by year(ordertime),
month(ordertime),
day(ordertime)
另外每日也可以这样:
select convert(char(8),ordertime,112) dt,
sum(Total) 销售合计
from 订单表
group by convert(char(8),ordertime,112)
查询当天:
select * from info where DateDiff(dd,datetime,getdate())=0
查询24小时内的:
select * from info where DateDiff(hh,datetime,getDate())<=24
本月记录
SELECT * FROM 表 WHERE datediff(month,[dateadd],getdate())=0
化作字符串比较
Select * From VIEW_CountBill Where Convert(varchar(10),[time],120) = Convert(varchar(10),getDate(),120)
常用SQL脚本记录一