经典Sql语句

**复制表结构**
select * into b from product where 1<>1
**拷贝表**
select * into c from product
**两张关联表,删除主表中已经在副表中没有的信息**
delete from product where not exists  (select * from userbase where product.uid=userbase.uid)
**取表里n到m条纪录**
<!--存在identity列-->
select * from product where identitycol between 5 and 10
<!--不存在indentity列-->
select identity(int) id0,* into #temp from product
select * from #temp where id0 >=1 and id0 <= 5
**删除重复纪录的sql语句**
<!--解决方案-->
/**1.将重复的记录记入temp1表**/
select  prodname, count(*) as counts  into   temp1   from  product  group by prodname  having count(*)>1
/**2.将不重复的记录记入temp1表**/
insert temp1 select prodname from product group by prodname having count(*)=1
/**3.作一个包含所有不重复记录的表**/
select * into temp2 from  temp1
or(实例)

--1、查找表中多余的重复记录,重复记录是根据单个字段(Name)来判断
select * from Msg_Company
where Name in (select Name from Msg_Company group by Name having count(Name) > 1) ----5141

--2、删除表中多余的重复记录,重复记录是根据单个字段(Name)来判断,只留有 SN 最小的记录
delete from Msg_Company
where Name in (select Name from Msg_Company group by Name having count(Name) > 1)
and SN not in (select min(SN) from Msg_Company group by Name having count(Name )>1)
/**4.删除重复表**/
delete from product
/**5.恢复表**/
select * into temp2 from product
where prodname in(select prodname from temp1)
/**6.删除临时表**/
drop table temp1
drop table temp2
/**第二种方案游标删除**/
declare @max integer,@id nvarchar(max)
declare cur_rows cursor local for select prodname,count(*) from product group by prodname having count(*) > 1
open cur_rows
fetch cur_rows into @id,@max
while @@fetch_status=0
begin
select @max = @max -1
set rowcount @max
delete from product where prodname= @id
fetch cur_rows into @id,@max
end
close cur_rows
set rowcount 0
**sql日期查询**
--a. 一个月的第一天
SELECT DATEADD(mm, DATEDIFF(mm,0,getdate()), 0)
--b. 本周的星期一
SELECT DATEADD(wk, DATEDIFF(wk,0,getdate()), 0)
--c. 一年的第一天
SELECT DATEADD(yy, DATEDIFF(yy,0,getdate()), 0)
--d. 季度的第一天
SELECT DATEADD(qq, DATEDIFF(qq,0,getdate()), 0)
--e. 上个月的最后一天
SELECT dateadd(ms,-3,DATEADD(mm, DATEDIFF(mm,0,getdate()), 0))
--f. 去年的最后一天
SELECT dateadd(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate()), 0))
--g. 本月的最后一天
SELECT dateadd(ms,-3,DATEADD(mm, DATEDIFF(m,0,getdate())+1, 0))
--h. 本月的第一个星期一
select DATEADD(wk, DATEDIFF(wk,0,
dateadd(dd,6-datepart(day,getdate()),getdate())
), 0)
--i. 本年的最后一天
SELECT dateadd(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate())+1, 0))。

你可能感兴趣的:(sql语句)