码迷,mamicode.com
首页 > 数据库 > 详细

常用SQL总结

时间:2015-05-04 13:45:07      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:

一 插入多行数据的几种方式

1 insert into target_table(column1,column2) select column1,5 from source_table;
target_table 表存在的时候
2 select * into target_table from source_table;
target_table 表不存在的时候
3 select * identity(int,1,1) As sid target_table from source_table
target_table 表不存在的时候, 插入标识符, 但是如果source_table 也有唯一标识符的时候,就不能把那个也插进去了

常用的的集中分页方式(30~40条数据)

1 不在前30条的前10条

SELECT top 10 *
FROM dbo.ActivityComment
WHERE id NOT IN
    ( SELECT top 30 id
     FROM [dbo].[ActivityComment] )

2 id大于第30条的id,的前10条

SELECT top 10 *
FROM dbo.ActivityComment
WHERE id >
    (SELECT max(id)
     FROM
       (SELECT top 30 id
        FROM dbo.ActivityComment
        ORDER BY id) AS ids)
ORDER BY id

3 利用 ROW_NUMBER() over(order by id) as num 来实现分页, 取出rumber 大于30的前10条

SELECT top 10 *
FROM
  ( SELECT ROW_NUMBER() over(ORDER BY id) AS num, * FROM dbo.SPProduct) AS a
WHERE num > 30

CET 的入门

1,用子查询解决

SELECT *
FROM dbo.SPProduct
WHERE id NOT in
    (SELECT id
     FROM dbo.SPProduct
     WHERE name LIKE %30%);

2,用存储过程解决

 定义表变量
declare @t table(SPProduct int)
把子查询的结果存入表变量
insert into @t(SPProduct)(select id from dbo.SPProduct where name like %30%)
再做外层查询
select * from dbo.SPProduct where id not in (select * from @t)

3 CTE方式

  with cr as (select id from SPProduct where name like %30%)
  select * from SPProduct where id not in (select * from cr)

4多个CET

  with cr1(id) as (select id from SPProduct where name like %30% union all select id from SPProduct where name like %20%)
  select * from SPProduct where id not in (select * from cr1)

 

常用SQL总结

标签:

原文地址:http://www.cnblogs.com/jgl5981/p/4475888.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!