SQL语句学习笔记(持续更新)

SQL脚本学习总结

1.删除表中所有数据
Delete from 表名 where 1=1 : 可以删除表中的数据,但是如果表的设计有自动增长的列,比如ID int identity(1,1),即使将表中的数据全部删除了自动增长的列也不会从1开始计数。
想要将表中的数据全部删除并且将自动增长列置为起始状态就要用这样一句SQL语句:truncate table表名

2.查询当前时间3个小时前的数据
select * from 表名 where 带有时间的字段 < (getdate()-0.125)
例子:select * from FlightAndSection where TimeOfStroage < (getdate()-0.125)
FlightAndSection 是我的表名,TimeOfStroage 是时间字段(类型:DateTime)

3.使用EXISTS关键字
EXISTS关键字的作用是在WHERE子句中测试子查询返回的数据行是否存在,但是子查询不会返回任何数据行,只产生逻辑值“true”或“false”。语法格式如下:
SELECT select_list
FROM table_source
WHERE EXISTS|NOT EXISTS(subquery)

4.当插入数据时表中如果已经存在此条数据则更新此条数据
if(exists (select * from 表 S1 where S1.字段1=条件1 ))
begin
 UPDATE 表 SET 字段2 = 数据1 WHERE (条件2)
 UPDATE 表 SET 字段3 = 数据2 WHERE (条件3)
end
例:
if(exists (select * from FlightAndSection S1 where S1.FlightCode=@FlightCode ))
begin
 UPDATE FlightAndSection SET SectionCode = SectionCode WHERE FlightCode = @FlightCode
 UPDATE FlightAndSection SET TimeOfStroage = @FTime WHERE FlightCode = @FlightCode 
end
我这个时写在触发器里面的语句,完整的SQL语句如下:
go
create trigger TR_Telephonics_Insert on Telephonics
for insert 
as
begin
	/*声明临时变量*/
	declare @TrackCode int				--存储航迹号 
	declare @FlightCode varchar(20)		--存储航班号
	declare @SectionCode varchar(20)	--存储扇区号
	declare @FTime	datetime 			--当时时间	
	/*给临时变量赋相应值*/
	select @TrackCode=SelfNum  from inserted
	select @FlightCode=FlightNum from inserted
	select @SectionCode=Section from inserted
	select @FTime=StorageTime from inserted
	
	if(exists (select * from FlightAndSection S1 where S1.FlightCode=@FlightCode ))
	begin
	 UPDATE FlightAndSection SET SectionCode = SectionCode WHERE FlightCode = @FlightCode
	 UPDATE FlightAndSection SET TimeOfStroage = @FTime WHERE FlightCode = @FlightCode 
	end
	/*更新航班表中数据*/
	else
	insert into FlightAndSection(TrackCode,FlightCode,SectionCode,TimeOfStroage) values(@TrackCode,@FlightCode,@SectionCode,@FTime)
end
go
5.查看自增序列最后一行
SELECT LAST_INSERT_ID();、
6.查看前5条数据
select * from news where 1=1 limit 0,5;










  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值