海海日记-冯海滨博客

您现在的位置是:首页 > 系统 > 正文

系统

SQL 语句收集

happyfhb2011-10-20系统1178

说明:复制表(只复制结构,源表名:a,新表名:b)
SQL: select * into b from a where 1<>1;

说明:拷贝表(拷贝数据,源表名:a,目标表名:b)
SQL: insert into b(a, b, c) select d, e, f from b;

说明:显示文章、提交人和最后回复时间
SQL: select a.title, a.username, b.adddate
from table a,(
select max(adddate) adddate
from table where table.title=a.title) b

说明:外连接查询(表名1:a,表名2:b)
SQL: select a.a, a.b, a.c, b.c, b.d, b.f
from a LEFT OUT JOIN b ON a.a = b.c;

说明:日程安排提前五分钟提醒
SQL: select *
from 日程安排
where datediff(’’minute’’, f开始时间, getdate())>5

说明:两张关联表,删除主表中已经在副表中没有的信息
SQL: delete from info
where not exists(
select *
from infobz
where info.infid=infobz.infid );


1.按姓氏笔画排序:
Select * From TableName order By CustomerName Collate Chinese_PRC_Stroke_ci_as

2.分页SQL语句
select * from(select (row_number() OVER (ORDER BY tab.ID Desc)) as rownum,tab.* from 表名 As tab) As t where rownum between 起始位置 And 结束位置

3.获取当前数据库中的所有用户表
select * from sysobjects where xtype='U' and category=0

4.获取某一个表的所有字段
select name from syscolumns where id=object_id('表名')

5.查看与某一个表相关的视图、存储过程、函数
select a.* from sysobjects a, syscomments b where a.id = b.id and b.text like '%表名%'

6.查看当前数据库中所有存储过程
select name as 存储过程名称 from sysobjects where xtype='P'

7.查询用户创建的所有数据库
select * from master..sysdatabases D where sid not in(select sid from master..syslogins where name='sa')
或者
select dbid, name AS DB_NAME from master..sysdatabases where sid <> 0x01

8.查询某一个表的字段和数据类型
select column_name,data_type from information_schema.columns
where table_name = '表名'

9.使用事务
在使用一些对数据库表的临时的SQL语句操作时,可以采用SQL SERVER事务处理,防止对数据操作后发现误操作问题
开始事务
Begin tran
Insert Into TableName Values(…)
SQL语句操作不正常,则回滚事务。
回滚事务
Rollback tran
SQL语句操作正常,则提交事务,数据提交至数据库。
提交事务
Commit tran
10. 按全文匹配方式查询
字段名 LIKE N'%[^a-zA-Z0-9]China[^a-zA-Z0-9]%'
or 字段名 LIKE N'%[^a-zA-Z0-9]China'
or 字段名 LIKE N'China[^a-zA-Z0-9]%'
or 字段名 LIKE N'China

11.计算执行SQL语句查询时间
declare @d datetime
set @d=getdate()
select * from SYS_ColumnProperties select [语句执行花费时间(毫秒)]=datediff(ms,@d,getdate())

12、说明:几个高级查询运算词
A: UNION 运算符
UNION 运算符通过组合其他两个结果表(例如 TABLE1 和 TABLE2)并消去表中任何重复行而派生出一个结果表。当 ALL 随 UNION 一起使用时(即 UNION ALL),不消除重复行。两种情况下,派生表的每一行不是来自 TABLE1 就是来自 TABLE2。
B: EXCEPT 运算符
EXCEPT 运算符通过包括所有在 TABLE1 中但不在 TABLE2 中的行并消除所有重复行而派生出一个结果表。当 ALL 随 EXCEPT 一起使用时 (EXCEPT ALL),不消除重复行。
C: INTERSECT 运算符
INTERSECT 运算符通过只包括 TABLE1 和 TABLE2 中都有的行并消除所有重复行而派生出一个结果表。当 ALL 随 INTERSECT 一起使用时 (INTERSECT ALL),不消除重复行。


计算一个库里各个表的记录总数:
select b.name,a.rowcnt from sysindexes a,sysobjects b
where a.id=b.id and a.indid<2 and b.xtype='u'

--统计数据库里每个表的详细情况
EXEC sp_MSforeachtable @command1="sp_spaceused '?'"

--获得每个表的记录数和容量:
EXEC sp_MSforeachtable @command1="print '?'",
@command2="sp_spaceused '?'",
@command3= "Select count(*) FROM ? "



DECLARE @dt datetime
SET @dt=GETDATE()

DECLARE @number int
SET @number=3

--1.指定日期该年的第一天或最后一天
--A. 年的第一天
Select CONVERT(char(5),@dt,120)+'1-1'

--B. 年的最后一天
Select CONVERT(char(5),@dt,120)+'12-31'


--2.指定日期所在季度的第一天或最后一天
--A. 季度的第一天
Select CONVERT(datetime,
CONVERT(char(8),
DATEADD(Month,
DATEPART(Quarter,@dt)*3-Month(@dt)-2,
@dt),
120)+'1')

--B. 季度的最后一天(CASE判断法)
Select CONVERT(datetime,
CONVERT(char(8),
DATEADD(Month,
DATEPART(Quarter,@dt)*3-Month(@dt),
@dt),
120)
+CASE WHEN DATEPART(Quarter,@dt) in(1,4)
THEN '31'ELSE '30' END)

--C. 季度的最后一天(直接推算法)
Select DATEADD(Day,-1,
CONVERT(char(8),
DATEADD(Month,
1+DATEPART(Quarter,@dt)*3-Month(@dt),
@dt),
120)+'1')


--3.指定日期所在月份的第一天或最后一天
--A. 月的第一天
Select CONVERT(datetime,CONVERT(char(8),@dt,120)+'1')

--B. 月的最后一天
Select DATEADD(Day,-1,CONVERT(char(8),DATEADD(Month,1,@dt),120)+'1')

--C. 月的最后一天(容易使用的错误方法)
Select DATEADD(Month,1,DATEADD(Day,-DAY(@dt),@dt))


--4.指定日期所在周的任意一天
Select DATEADD(Day,@number-DATEPART(Weekday,@dt),@dt)


--5.指定日期所在周的任意星期几
--A. 星期天做为一周的第1天
Select DATEADD(Day,@number-(DATEPART(Weekday,@dt)+@@DATEFIRST-1)%7,@dt)

--B. 星期一做为一周的第1天
Select DATEADD(Day,@number-(DATEPART(Weekday,@dt)+@@DATEFIRST-2)%7-1,@dt)



1 :普通SQL语句可以用exec执行

Select * from tableName
exec('select * from tableName')
exec sp_executesql N'select * from tableName' -- 请注意字符串前一定要加N

2:字段名,表名,数据库名之类作为变量时,必须用动态SQL

declare @fname varchar(20)
set @fname = 'FiledName'
Select @fname from tableName -- 错误,不会提示错误,但结果为固定值FiledName,并非所要。
exec('select ' + @fname + ' from tableName') -- 请注意 加号前后的 单引号的边上加空格

当然将字符串改成变量的形式也可
declare @fname varchar(20)
set @fname = 'FiledName' --设置字段名

declare @s varchar(1000)
set @s = 'select ' + @fname + ' from tableName'
exec(@s) -- 成功
exec sp_executesql @s -- 此句会报错

declare @s Nvarchar(1000) -- 注意此处改为nvarchar(1000)
set @s = 'select ' + @fname + ' from tableName'
exec(@s) -- 成功
exec sp_executesql @s -- 此句正确

3. 输出参数
declare @num int, @sqls nvarchar(4000)
set @sqls='select count(*) from tableName'
exec(@sqls)

--如何将exec执行结果放入变量中?

declare @num int, @sqls nvarchar(4000)
set @sqls='select @a=count(*) from tableName '
exec sp_executesql @sqls,N'@a int output',@num output
select @num


1 :普通SQL语句可以用Exec执行 例: Select * from tableName
Exec('select * from tableName')
Exec sp_executesql N'select * from tableName' -- 请注意字符串前一定要加N

2:字段名,表名,数据库名之类作为变量时,必须用动态SQL

错误: declare @fname varchar(20)
set @fname = 'FiledName'
Select @fname from tableName -- 错误,不会提示错误,但结果为固定值FiledName,并非所要。
正确: Exec('select ' + @fname + ' from tableName') -- 请注意加号前后的单引号的边上加空格

当然将字符串改成变量的形式也可
declare @fname varchar(20)
set @fname = 'FiledName' --设置字段名

declare @s varchar(1000)
set @s = 'select ' + @fname + ' from tableName'
Exec(@s) -- 成功
exec sp_executesql @s -- 此句会报错

--注:@s参数必须为ntext或nchar或nvarchar类型,必须将declare @s varchar(1000) 改为declare @s Nvarchar(1000)



如下:
declare @s Nvarchar(1000) -- 注意此处改为nvarchar(1000)

set @fname = 'FiledName' --设置字段名
set @s = 'select ' + @fname + ' from tableName'
Exec(@s) -- 成功
exec sp_executesql @s -- 此句正确

3. 输入或输出参数

(1)输入参数:
declare @QueryString nvarchar(1000) --动态查询语句变量(注:必须为ntext或nchar哐nvarchar类型,不能是varchar类型)
declare @paramstring nvarchar(200) --设置动态语句中的参数的字符串(注:必须为ntext或nchar哐nvarchar类型,不能是varchar类型)
declare @input_id int--定义需传入动态语句的参数的值

set @QueryString='select * from tablename where id=@id' --id为字段名,@id为要传入的参数
set @paramstring='@id int' --设置动态语句中参数的定义的字符串
set @input_id =1 --设置需传入动态语句的参数的值为1
exec sp_executesql @querystring,@paramstring,@id=@input_id  
若有多个参数:
declare @QueryString nvarchar(1000) --动态查询语句变量(注:必须为ntext或nchar哐nvarchar类型,不能是varchar类型)
declare @paramstring nvarchar(200) --设置动态语句中的参数的字符串(注:必须为ntext或nchar哐nvarchar类型,不能是varchar类型)
declare @input_id int--定义需传入动态语句的参数的值,参数1
declare @input_name varchar(20)--定义需传入动态语句的参数的值,参数2

set @QueryString='select * from tablename where id=@id and name=@name' --id与name为字段名,@id与@name为要传入的参数
set @paramstring='@id int,@name varchar(20)' --设置动态语句中参数的定义的字符串,多个参数用","隔开
set @input_id =1 --设置需传入动态语句的参数的值为1
set @input_name='张三' --设置需传入动态语句的参数的值为"张三"
exec sp_executesql @querystring,@paramstring,@id=@input_id,@name=@input_name --请注意参数的顺序
(2)输出参数
declare @num int, @sqls nvarchar(4000)
set @sqls='select count(*) from tableName'
exec(@sqls)
--如何将exec执行结果放入变量中?
declare @QueryString nvarchar(1000) --动态查询语名变量(注:必须为ntext或nchar哐nvarchar类型,不能是varchar类型)
declare @paramstring nvarchar(200) --设置动态语句中的参数的字符串(注:必须为ntext或nchar哐nvarchar类型,不能是varchar类型)
declare @output_result int--查询结果赋给@output_result

set @QueryString='select @totalcount=count(*) from tablename' --@totalcount 为输出结果参数
set @paramstring='@totalcount int output' --设置动态语句中参数的定义的字符串,多个参数用","隔开
exec sp_executesql @querystring,@paramstring,@totalcount=@output_result output
select @output_result
当然,输入与输出参数可以一起使用,大家可以自己去试一试。
另外,动态语句查询的结果集要输出的话,我只想到以下用临时表的方法,不知各位有没有更好的方法.
IF object_id('[tempdb].[dbo].#tmp') IS NOT NULL --判断临时表#tmp是否存在,存在则删除
drop table #tmp
select * into #tmp from tablename where 1=2 --创建临时表#tmp,其结构与tablename相同

declare @QueryString nvarchar(1000) --动态查询语名变量(注:必须为ntext或nchar哐nvarchar类型,不能是varchar类型)
set @QueryString='select * from tablename '
insert into #tmp(field1,field2,...) exec(@querystirng)




1、说明:复制表(只复制结构,源表名:a 新表名:b) (Access可用)
法一:select * into b from a where 1 <>1
法二:select top 0 * into b from a

2、说明:拷贝表(拷贝数据,源表名:a 目标表名:b) (Access可用)
insert into b(a, b, c) select d,e,f from a;

3、说明:跨数据库之间表的拷贝(具体数据使用绝对路径) (Access可用)
insert into b(a, b, c) select d,e,f from b in ‘具体数据库’ where 条件
例子:..from b in '"&Server.MapPath(".")&"/data.mdb" &"' where..

4、说明:子查询(表名1:a 表名2:b)
select a,b,c from a where a IN (select d from b ) 或者: select a,b,c from a where a IN (1,2,3)

5、说明:显示文章、提交人和最后回复时间
select a.title,a.username,b.adddate from table a,(select max(adddate) adddate from table where table.title=a.title) b

6、说明:外连接查询(表名1:a 表名2:b)
select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c

7、说明:在线视图查询(表名1:a )
select * from (Select a,b,c FROM a) T where t.a > 1;

8、说明:between的用法,between限制查询数据范围时包括了边界值,not between不包括
select * from table1 where time between time1

9、说明:in 的使用方法
select * from table1 where a [not] in (‘值1’,’值2’,’值4’,’值6’)

10、说明:两张关联表,删除主表中已经在副表中没有的信息
delete from table1 where not exists ( select * from table2 where table1.field1=table2.field1 )

11、说明:四表联查问题:
select * from a left inner join b on a.a=b.b right inner join c on a.a=c.c inner join d on a.a=d.d where .....

12、说明:日程安排提前五分钟提醒
SQL: select * from 日程安排 where datediff('minute',f开始时间,getdate())>5

13、说明:一条sql 语句搞定数据库分页
select top 10 b.* from (select top 20 主键字段,排序字段 from 表名 order by 排序字段 desc) a,表名 b where b.主键字段 = a.主键字段 order by a.排序字段

14、说明:前10条记录
select top 10 * form table1 where 范围

15、说明:选择在每一组b值相同的数据中对应的a最大的记录的所有信息(类似这样的用法可以用于论坛每月排行榜,每月热销产品分析,按科目成绩排名,等等.)
select a,b,c from tablename ta where a=(select max(a) from tablename tb where tb.b=ta.b)

16、说明:包括所有在 TableA 中但不在 TableB和TableC 中的行并消除所有重复行而派生出一个结果表
(select a from tableA ) except (select a from tableB) except (select a from tableC)

17、说明:随机取出10条数据
select top 10 * from tablename order by newid()

18、说明:随机选择记录
select newid()

19、说明:删除重复记录
Delete from tablename where id not in (select max(id) from tablename group by col1,col2,...)

20、说明:列出数据库里所有的表名
select name from sysobjects where type='U'

21、说明:列出表里的所有的列
select name from syscolumns where id=object_id('TableName')

22、说明:列示type、vender、pcs字段,以type字段排列,case可以方便地实现多重选择,类似select 中的case。
select type,sum(case vender when 'A' then pcs else 0 end),sum(case vender when 'C' then pcs else 0 end),sum(case vender when 'B' then pcs else 0 end) FROM tablename group by type
显示结果:
type vender pcs
电脑 A 1
电脑 A 1
光盘 B 2
光盘 A 2
手机 B 3
手机 C 3

23、说明:初始化表table1
TRUNCATE TABLE table1

24、说明:选择从10到15的记录
select top 5 * from (select top 15 * from table order by id asc) table_别名 order by id desc

declare @a varchar(100),@b varchar(20)
select @a='abcdefbcmnbcde',@b='bc'
select (len(@a)-len(replace(@a,@b,'')))/len(@b)

说明:选择在每一组b值相同的数据中对应的a最大的记录的所有信息(类似这样的用法可以用于论坛每月排行榜,每月热销产品分析,按科目成绩排名,等等.)
select a,b,c from tablename ta where a=(select max(a) from tablename tb where tb.b=ta.b)

平淡中储蓄成长

发表评论

评论列表

  • 这篇文章还没有收到评论,赶紧来抢沙发吧~