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;