首页 > 代码库 > 数据库操作----找了MySQL和SQL Sever两个的基础语句

数据库操作----找了MySQL和SQL Sever两个的基础语句

这是MySQL的基本操作:
1
登入数据库:mysql -uroot -p+密码 (SQL Sever登入: osql -U 用户名 -P 密码) 2 显示已存在的数据库:show databases; 3 使用某个数据库:use+数据库名; 4 显示某个数据库下已存在的关系表:show tables; 5 6 查看某个关系表所有数据:select * from tableName; 7 查看某个关系表部分字段数据:select 字段1,字段2,...,字段n from tableName; 8 查看n条记录:select ... from ... limit n; 9 查看第i条到第j条之间的记录:select ... from ... limit i,j; 10 11 使用order by 来对记录进行排序,默认从小到大 12 >select stuName, stuScore from student order by stuScore desc; //(从大到小) 13 >select stuName, stuScore from student order by stuScore asc; //(从小到大) 14 15 去重: distinct 16 >select distinct stuCourse from student; 17 > select count(distinct stuCourse) from student; 18 19 20 聚合函数(常用于GROUP BY从句的SELECT查询中) 21 AVG(col)返回指定列的平均值 22 COUNT(col)返回指定列中非NULL值的个数 23 MIN(col)返回指定列的最小值 24 MAX(col)返回指定列的最大值 25 SUM(col)返回指定列的所有值之和 26 GROUP_CONCAT(col) 返回由属于一组的列值连接组合而成的结果 27 > select stuCourse, sum(stuScore) from student where stuCourse = "Chinese"; 28 > select stuCourse, sum(stuScore) from student group by stuCourse; 29 > select stuCourse, avg(stuScore) from student group by stuCourse; 30 > select stuCourse, max(stuScore) from student group by stuCourse; 31 > select stuCourse, min(stuScore) from student group by stuCourse; 32 > select avg(stuAge) as avg_age from student; 33 > select group_concat(stuName, stuCourse) from student; 34 35 条件限制:where : =, !=, >, >=, <, <=, and, not, or 36 , between...and..., not between...and... 37 , is null, is not null, like(%, _), not like(%, _) 38 , in(项1, 项2, …), not in(项1, 项2, …) 39 , exists, not exists 40 , any, some, all 41 42 %: 匹配任意个字符 43 _:匹配单个字符 44 45 创建数据库:create database 数据库名; 46 创建关系表:create table tableName(字段1 类型 限制,字段2 类型 限制,...,字段n 类型 限制); 47 显示关系表的格式:show create table tableName; 48 更新数据:update tableName set 字段1 = 字段1值, 字段2 = 字段2值, ..., 字段n = 字段n值; 49 50 插入数据:insert tableName(字段1,字段2,...,字段n) values(字段1值,字段2值,...,字段n值); 51 52 生成一个关系表的备份:create table baktableName (select * from tableName); 53 使用备份的数据对新表插入数据 54 > insert book select * from bookBak; 55 56 生成一个数据库的备份:mysqldump -uUserName -p dbname > bakefile; 57 使用数据库的备份恢复数据库:mysql -uUserName -p dbname < bakefile; 58 59 使用交互方式恢复数据库: 60 > create database dbName; (如果不存在这个数据库) 61 > use dbName; 62 > source bakeFile; 63 64 删除一个数据库:drop database dbname; 65 删除关系表中所有数据:delete from tableName; 66 删除关系表中符合条件的数据:delete from tableName where...; 67 68 给关系表增加一个字段:alter table tableName add 字段名 说明(default H); 69 给关系表删除一个字段:alter table tableName drop 字段名; 70 给关系表修改一个字段:alter table tableName modify 字段名 说明; 71 给关系表修改一个字段:alter table tableName change 旧字段名 新字段名 说明(类型...); 72 73 设置字段值唯一,即该字段的值不允许有重复的: unique 74 > create table tmp(id int unique not null, name varchar(32)); 75 76 主键:唯一标识一条记录,主键可以是单个字段,也可以是多个字段合成的 77 > alter table student modify stuId varchar(32) primary key not null; 78 79 > create table book(bookId bigint auto_increment primary key not null, bookName varchar(32) not null); 80 > create table book(bookId bigint auto_increment not null, bookName varchar(32) not null, primary key(bookId)); 81 82 > create table score(stuId varchar(32) not null, 83 > bookId bigInt not null, 84 > score float, 85 > primary key(stuId, bookId)); 86 87 多表查询 88 > select score.bookId, stuName, bookName from score, student, book where score.bookId = book.bookId and score.stuId = student.stuId; 89 > select score.bookId, stuName, bookName, score from score, student, book where score.bookId = book.bookId and score.stuId = student.stuId; 90 91 外键 92 > alter table score add constraint stuId_cons foreign key(stuId) references student(stuId); 93 > alter table score add constraint bookId_cons foreign key(bookId) references book(bookId); 94 95 > create table tecbook(tecId varchar(32) not null, bookId bigint not null, primary key(tecId, bookId), foreign key(tecId) references teacher(tecId), foreign key(bookId) references book(bookId)); 96 97 98 99 学生表student(stuId,stuName,stuAge,stuSex) 100 mysql> create table student(stuId varchar(32) primary key not null, 101 -> stuName varchar(32) not null, 102 -> stuAge int, 103 -> stuSex char); 104 105 教师表 teacher(tecId,tecName) 106 mysql> create table teacher(tecId varchar(32) primary key not null, 107 -> tecName varchar(32) not null); 108 109 课程表course(courseId,courseName,tecId) 110 mysql> create table course(courseId bigint primary key auto_increment not null, 111 -> courseName varchar(32) not null, 112 -> tecId varchar(32) not null, 113 -> foreign key(tecId) references teacher(tecId) on update cascade on delete cascade); 114 115 成绩表score(stuId,courseId,score,note) 116 mysql> create table score(stuId varchar(32) not null, 117 -> courseId bigint not null, 118 -> score float, 119 -> note varchar(64), 120 -> primary key(stuId, courseId), 121 -> foreign key(stuId) references student(stuId) on delete cascade on update cascade, 122 -> foreign key(courseId) references course(courseId) on delete no action on update cascade); 123 124 125 级联操作: 126 foreign key(column) references tableName(column) 127 [[on delete | on update] [cascade | no action | set null | restrict]]; 128 129 130 查询每个学生每门课的成绩 131 > select stuName, courseName, score from student, course, score where student.stuId = score.stuId 132 and course.courseId = score.courseId; 133 134 查询每个学生的总成绩 135 > select stuName, sum(score) from student, course, score where student.stuId = score.stuId 136 and course.courseId = score.courseId group by stuName; 137 138 对每个学生的总成绩排序 139 > select stuName, sum(score) as sum_score from student, course, score where student.stuId = score.stuId 140 and course.courseId = score.courseId group by stuName order by sum_score desc; 141 142 查询每个学生的平均成绩 143 > select stuName, avg(score) from student, course, score where student.stuId = score.stuId 144 and course.courseId = score.courseId group by stuName; 145 146 查询平均成绩>80的学生 147 > select stuName, avg(score) as avg_score from student, course, score where student.stuId = score.stuId and course.courseId = score.courseId group by stuName having avg_score > 80; 148 Note: having字句可以让我们筛选成组后的各种数据,where字句在聚合前先筛选记录,也就是说作用在group by和having字句前。而 having子句在聚合后对组记录进行筛选。 149 150 查询“3004”课程比“3002”课程成绩高的所有学生的学号 151 > select t1.stuId from (select stuId, score from score where courseId = 3002) as t1, 152 (select stuId, score from score where courseId = 3004) as t2 where t1.score < t2.score 153 and t1.stuId = t2.stuId; 154 155 > select stuId from score s1 where courseId = 3002 and score < 156 (select score from score s2 where courseId = 3004 and s1.stuId = s2.stuId); 157 158 > select s1.stuId from score s1, score s2 where s1.score < s2.score and s1.stuId = s2.stuId 159 and s1.courseId = 3002 and s2.courseId = 3004; 160 161 查询所有同学的学号、姓名、课数、总成绩 162 > select score.stuId, stuName, count(courseId) as course_num, sum(score) as sum_score from score, student where score.stuId = student.stuId group by stuId; 163 164 查询和likui性别相同的学生信息 165 > select stuId, stuName from student where stuSex = (select stuSex from student where stuName = "likui") 166 and stuName != "likui"; 167 168 查询没学过“mozi”老师课的同学的学号、姓名 169 > select distinct score.stuId, stuName from score, student where score.stuId = student.stuId 170 and score.stuId != 171 ( 172 select stuId from score where courseId in 173 ( 174 select courseId from course where tecId = 175 (select tecId from teacher where tecName = "mozi") 176 ) 177 ); 178 179 查询每个老师所教课程平均分从高到低显示 180 > select c.courseId, c.courseName, avg(sc.score) avgScore, t.tecName from course c, score sc, teacher t where c.courseId = sc.courseId and c.tecId = t.tecId group by(sc.courseId) order by avgScore DESC; 181 182 > select course.tecId, teacher.tecName, t1.courseId, t1.avg_score from (select courseId, avg(score) as avg_score from score group by courseId) as t1, course, teacher where t1.courseId = course.courseId and course.tecId = teacher.tecId; 183 184 删除学习“laozi”老师课的score表记录 185 > delete from score where courseId in (select courseId from course 186 where tecId = (select tecId from teacher where tecName = "laozi")); 187 188 查询两门及以上不及格课程的同学的学号及其平均成绩 189 > select stuId, avg(score) from score where stuId in (select stuId from score where score < 60 group by stuId having count(*) >= 2) group by stuId; 190 191 > select stuId, avg(score) from score where stuId in (select stuId from (select stuId, count(*) as blow from score where score < 60 group by stuId having blow >= 2)as t1) group by stuId; 192 193 查询各科成绩最高和最低的分:以如下形式显示:课程ID,最高分,最低分 194 > select courseId, max(score), min(score) from score group by courseId; 195 196 查询学过“3001”并且也学过编号“3003”课程的同学的学号、姓名 197 > select stuId, stuName from student where stuId in (select s1.stuId from score s1, score s2 where s1.courseId = 3001 and s2.courseId = 3003 and s1.stuId = s2.stuId); 198 199 查询“3001”课程的分数比“3001”课程平均分低的学生stuId, stuName 200 > select stuId, stuName from student where stuId in(select stuId from score where score < (select avg(score) from score where courseId = 3001) and courseId = 3001); 201 202 查询“3001”课程的分数比“3001”课程平均分低的学生stuId, stuName, score 203 > select score.stuId, stuName, score from score, student where score < (select avg(score) from score 204 where courseId = 3001) and courseId = 3001 and score.stuId = student.stuId; 205 206 查询“3001”课程的分数比“3001”课程平均分低的学生stuId, stuName, score, avg_score 207 > select score.stuId, stuName, (select avg(score) from score where courseId = 3001) as avg_score, score from score, student where score < (select avg(score) from score where courseId = 3001) and courseId = 3001 and score.stuId = student.stuId; 208 209 210 view: 是视图,是一张虚表,表中没有任何数据 211 > create view score_view as select score.stuId, stuName, count(courseId) as course_num, sum(score) as sum_score from score, student where score.stuId = student.stuId group by stuId; 212 213 > select * from score_view; 214 215 存储过程: 216 delimiter $$ 217 create procedure proName(in | out | inout) 218 begin 219 commands; 220 end 221 $$ 222 223 224 mysql> delimiter // 225 mysql> create procedure pro_new() 226 -> begin 227 -> select * from student; 228 -> select * from course; 229 -> select * from teacher; 230 -> end 231 -> // 232 mysql> delimiter ; 233 mysql> call pro_new; 234 235 236 237 mysql> delimiter // 238 mysql> create procedure addTec(in id varchar(32), in name varchar(32)) 239 -> begin 240 -> insert teacher(tecId, tecName) values(id, name); 241 -> end 242 -> // 243 244 mysql> delimiter ; 245 mysql> call addTec("2010", "daai"); 246 247 248 mysql> delimiter // 249 mysql> create procedure pp(out op int) 250 -> begin 251 -> set op = 90; 252 -> end 253 -> // 254 255 mysql> delimiter ; 256 mysql> set @opp = 0; 257 mysql> select @opp; 258 mysql> call pp(@opp); 259 mysql> select @opp; 260 261 262 1, if-then-else 分支 263 if condition then 264 commands; 265 [elseif condition then 266 commands;] 267 [else 268 commands;] 269 end if; 270 271 mysql> delimiter // 272 mysql> create procedure sala_pro4(in level int) 273 > begin 274 > if level = 2 then 275 > update teacher set tecSalary = 5000 where tecLevel = level; 276 > elseif level = 3 then 277 > update teacher set tecSalary = 7000 where tecLevel = level; 278 > elseif level = 4 then 279 > update teacher set tecSalary = 9000 where tecLevel = level; 280 > else 281 > select * from teacher; 282 > end if; 283 > end// 284 285 > show create procedure proName; 286 > show procedure status; 287 > drop procedure proName; 288 289 290 2case 分支 291 case expression 292 when value1 then 293 commands; 294 [when value2 then 295 commands;] 296 [else 297 commands;] 298 end case; 299 300 mysql> create procedure tec_pro(in level int) 301 > begin 302 > case level 303 > when 1 then 304 > update teacher set tecSalary = 4000 where tecLevel = 1; 305 > when 2 then 306 > update teacher set tecSalary = 4500 where tecLevel = 2; 307 > when 3 then 308 > update teacher set tecSalary = 6000 where tecLevel = 3; 309 > when 3 then 310 > update teacher set tecSalary = 6000 where tecLevel = 3; 311 > when 4 then 312 > update teacher set tecSalary = 8000 where tecLevel = 4; 313 > else 314 > select * from teacher; 315 > end case; 316 > end// 317 318 319 while 循环 320 [loopName:] while condition do 321 commands; 322 end while [loopName]; 323 324 mysql> create procedure show_pro(in id bigint) 325 > begin 326 > declare var int; 327 > set var = 0; 328 > while var < 6 do 329 > select * from course where courseId = id + var; 330 > set var = var + 1; 331 > end while; 332 > end// 333 334 335 repeat-until 循环 336 [loopName:] repeat 337 commands; 338 until condition 339 end repeat [loopName]; 340 341 mysql> create procedure ins_pro2(in name varchar(32)) 342 > begin 343 > declare tim int; 344 > set tim = 1; 345 > repeat 346 > insert usename(Name, Time, Level) values(name, tim, tim); 347 > set tim = tim + 1; 348 > until tim > 8 349 > end repeat; 350 > end// 351 352 353 354 loop 循环 355 loopName: loop 356 commands; 357 end loop loopName; 358 359 360 函数创建: 361 create function(...) returns valueType 362 begin 363 commands; 364 return value; 365 end 366 367 mysql> create function test(n int) returns text 368 > begin 369 > declare i int default 0; 370 > declare s text default ‘‘; 371 > myloop: loop 372 > set i = i + 1; 373 > set s = concat(s, "*"); 374 > if i >= n then 375 > leave myloop; 376 > end if; 377 > end loop myloop; 378 > return s; 379 > end// 380 381 mysql> select test(4); 382 mysql> set @tt = test(3); 383 384 385 1,游标定义:declare cursorName cursor for select... 386 2,打开游标:open cursorName 387 3,使用fetch cursorName into var1,var2,...命令去遍历select结果数据表里的数据记录 388 4,关闭游标:close cursorName(游标会在对它们做出声明的 begin-end 语句块执行终了时自动随之结束) 389 备注:若使用fetch命令把select结果数据表的记录都读完了会出发一个错误:no data to fetch。 390 对于该错误可以定义一个错误处理器来捕获。出错处理条件一般使用 not found 即可 391 392 mysql> create procedure cur_pro2() 393 > begin 394 > declare result varchar(256) default ‘‘; 395 > declare name varchar(32); 396 > declare done int default 0; 397 > declare cur_book cursor for select courseName from course; 398 > declare continue handler for not found set done = 1; 399 > open cur_book; 400 > repeat 401 > fetch cur_book into name; 402 > set result = concat(result, name); 403 > until done 404 > end repeat; 405 > select result; 406 > close cur_book; 407 > end//

下面是SQL Sever的语法,其实基本上差不多,这两天我所用到,大概也就一个递增、一个级联不同

一、基础

1、说明:创建数据库
CREATE DATABASE database-name 
2、说明:删除数据库
drop database dbname
3、说明:备份sql server
— 创建 备份数据的 device
USE master
EXEC sp_addumpdevice ‘disk’, ‘testBack’, ‘c:\mssql7backup\MyNwind_1.dat’
— 开始 备份
BACKUP DATABASE pubs TO testBack
4、说明:创建新表
create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..)

根据已有的表创建新表: 
A:create table tab_new like tab_old (使用旧表创建新表)
B:create table tab_new as select col1,col2… from tab_old definition only
5、说明:删除新表
drop table tabname
6、说明:增加一个列
Alter table tabname add column col type
注:列增加后将不能删除。DB2中列加上后数据类型也不能改变,唯一能改变的是增加varchar类型的长度。
7、说明:添加主键: Alter table tabname add primary key(col)
说明:删除主键: Alter table tabname drop primary key(col) 
8、说明:创建索引:create [unique] index idxname on tabname(col….)
删除索引:drop index idxname
注:索引是不可更改的,想更改必须删除重新建。
9、说明:创建视图:create view viewname as select statement 
删除视图:drop view viewname
10、说明:几个简单的基本的sql语句


选择:select * from table1 where 范围
插入:insert into table1(field1,field2) values(value1,value2)
删除:delete from table1 where 范围
更新:update table1 set field1=value1 where 范围
查找:select * from table1 where field1 like ’%value1%’ —like的语法很精妙,查资料!
排序:select * from table1 order by field1,field2 [desc]
总数:select count as totalcount from table1
求和:select sum(field1) as sumvalue from table1
平均:select avg(field1) as avgvalue from table1
最大:select max(field1) as maxvalue from table1
最小:select min(field1) as minvalue from table1
11、说明:几个高级查询运算词
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),不消除重复行。
注:使用运算词的几个查询结果行必须是一致的。
12、说明:使用外连接
A、left (outer) join:
左外连接(左连接):结果集几包括连接表的匹配行,也包括左连接表的所有行。
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
B:right (outer) join: 
右外连接(右连接):结果集既包括连接表的匹配连接行,也包括右连接表的所有行。
C:full/cross (outer) join:
全外连接:不仅包括符号连接表的匹配行,还包括两个连接表中的所有记录。
12、分组:Group by:
一张表,一旦分组 完成后,查询后只能得到组相关的信息。
组相关的信息:(统计信息) count,sum,max,min,avg 分组的标准)
在SQLServer中分组时:不能以text,ntext,image类型的字段作为分组依据
在selecte统计函数中的字段,不能和普通的字段放在一起;

13、对数据库进行操作:
分离数据库: sp_detach_db;附加数据库:sp_attach_db 后接表明,附加需要完整的路径名
14.如何修改数据库的名称:
sp_renamedb ‘old_name’, ‘new_name’

二、提升
1、说明:复制表(只复制结构,源表名:a 新表名:b) (Access可用)
法一:select * into b from a where 1<>1(仅用于SQlServer)
法二:select top 0 * into b from a
2、说明:拷贝表(拷贝数据,源表名:a 目标表名:b) (Access可用)
insert into b(a, b, c) select d,e,f from b;

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 and time2
select a,b,c, from table1 where a not between 数值1 and 数值2

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.排序字段
具体实现:
关于数据库分页:

declare @start int,@end int

@sqlnvarchar(600)

set @sql=’select top’+str(@end-@start+1)+’+from T where rid not in(select top’+str(@str-1)+’Rid from T where Rid>-1)’

exec sp_executesql @sql


注意:在top后不能直接跟一个变量,所以在实际应用中只有这样的进行特殊的处理。Rid为一个标识列,如果top后还有具体的字段,这样做是非常有好处的。因为这样可以避免 top的字段如果是逻辑索引的,查询的结果后实际表中的不一致(逻辑索引中的数据有可能和数据表中的不一致,而查询时如果处在索引则首先查询索引)

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、说明:删除重复记录
1),delete from tablename where id not in (select max(id) from tablename group by col1,col2,…)
2),select distinct * into temp from tablename
delete from tablename
insert into tablename select * from temp
评价: 这种操作牵连大量的数据的移动,这种做法不适合大容量但数据操作
3),例如:在一个外部表中导入数据,由于某些原因第一次只导入了一部分,但很难判断具体位置,这样只有在下一次全部导入,这样也就产生好多重复的字段,怎样删除重复字段

alter table tablename
–添加一个自增列
addcolumn_b int identity(1,1)
delete from tablename where column_b not in(
select max(column_b)from tablename group by column1,column2,…)
alter table tablename drop column column_b

20、说明:列出数据库里所有的表名
select name from sysobjects where type=’U’ // 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

三、技巧

11=11=2的使用,在SQL语句组合时用的较多

“where 1=1” 是表示选择全部 “where 1=2”全部不选,
如:
if @strWhere !=”
begin
set @strSQL = ‘select count(*) as Total from [ + @tblName + ] where ‘ + @strWhere
end
else
begin
set @strSQL = ‘select count(*) as Total from [ + @tblName + ]‘
end

我们可以直接写成

错误!未找到目录项。
set @strSQL = ‘select count(*) as Total from [ + @tblName + ] where 1=1 安定 ‘+ @strWhere 2、收缩数据库
–重建索引
DBCC REINDEX
DBCC INDEXDEFRAG
–收缩数据和日志
DBCC SHRINKDB
DBCC SHRINKFILE

3、压缩数据库
dbcc shrinkdatabase(dbname)

4、转移数据库给新用户以已存在用户权限
exec sp_change_users_login ‘update_one’,newname’,oldname’
go

5、检查备份集
RESTORE VERIFYONLY from disk=’E:\dvbbs.bak’

6、修复数据库
ALTER DATABASE [dvbbs] SET SINGLE_USER
GO
DBCC CHECKDB(‘dvbbs’,repair_allow_data_loss) WITH TABLOCK
GO
ALTER DATABASE [dvbbs] SET MULTI_USER
GO

7、日志清除
SET NOCOUNT ON
DECLARE @LogicalFileName sysname,
@MaxMinutes INT,
@NewSize INT


USE tablename — 要操作的数据库名
SELECT @LogicalFileName = ‘tablename_log’, — 日志文件名
@MaxMinutes = 10, — Limit on time allowed to wrap log.
@NewSize = 1 — 你想设定的日志文件的大小(M)

Setup / initialize
DECLARE @OriginalSize int
SELECT @OriginalSize = size
FROM sysfiles
WHERE name = @LogicalFileName
SELECT ‘Original Size of ‘ + db_name() + ‘ LOG is ‘ +
CONVERT(VARCHAR(30),@OriginalSize) + ‘ 8K pages or ‘ +
CONVERT(VARCHAR(30),(@OriginalSize*8/1024)) + ‘MB’
FROM sysfiles
WHERE name = @LogicalFileName
CREATE TABLE DummyTrans
(DummyColumn char (8000) not null)


DECLARE @Counter INT,
@StartTime DATETIME,
@TruncLog VARCHAR(255)
SELECT @StartTime = GETDATE(),
@TruncLog = ‘BACKUP LOG ‘ + db_name() + ‘ WITH TRUNCATE_ONLY’

DBCC SHRINKFILE (@LogicalFileName, @NewSize)
EXEC (@TruncLog)
– Wrap the log if necessary.
WHILE @MaxMinutes > DATEDIFF (mi, @StartTime, GETDATE()) — time has not expired
AND @OriginalSize = (SELECT size FROM sysfiles WHERE name = @LogicalFileName)
AND (@OriginalSize * 8 /1024) > @NewSize
BEGIN — Outer loop.
SELECT @Counter = 0
WHILE ((@Counter < @OriginalSize / 16) AND (@Counter < 50000))
BEGIN — update
INSERT DummyTrans VALUES (‘Fill Log’) DELETE DummyTrans
SELECT @Counter = @Counter + 1
END
EXEC (@TruncLog)
END
SELECT ‘Final Size of ‘ + db_name() + ‘ LOG is ‘ +
CONVERT(VARCHAR(30),size) + ‘ 8K pages or ‘ +
CONVERT(VARCHAR(30),(size*8/1024)) + ‘MB’
FROM sysfiles
WHERE name = @LogicalFileName
DROP TABLE DummyTrans
SET NOCOUNT OFF

8、说明:更改某个表
exec sp_changeobjectowner ‘tablename’,dbo’

9、存储更改全部表

CREATE PROCEDURE dbo.User_ChangeObjectOwnerBatch
@OldOwner as NVARCHAR(128),
@NewOwner as NVARCHAR(128)
AS

DECLARE @Name as NVARCHAR(128)
DECLARE @Owner as NVARCHAR(128)
DECLARE @OwnerName as NVARCHAR(128)

DECLARE curObject CURSOR FOR
select ‘Name’ = name,
‘Owner’ = user_name(uid)
from sysobjects
where user_name(uid)=@OldOwner
order by name

OPEN curObject
FETCH NEXT FROM curObject INTO @Name, @Owner
WHILE(@@FETCH_STATUS=0)
BEGIN
if @Owner=@OldOwner
begin
set @OwnerName = @OldOwner + ‘.’ + rtrim(@Name)
exec sp_changeobjectowner @OwnerName, @NewOwner
end
– select @name,@NewOwner,@OldOwner

FETCH NEXT FROM curObject INTO @Name, @Owner
END

close curObject
deallocate curObject
GO


10、SQL SERVER中直接循环写入数据
declare @i int
set @i=1
while @i<30
begin
insert into test (userid) values(@i)
set @i=@i+1
end
案例:
有如下表,要求就裱中所有沒有及格的成績,在每次增長0.1的基礎上,使他們剛好及格:

Namescore

Zhangshan80

Lishi 59

Wangwu 50

Songquan69

while((select min(score) from tb_table)<60)

begin

update tb_table set score =score*1.01

where score<60

if(select min(score) from tb_table)>60

break

else

continue

end

数据开发-经典

1.按姓氏笔画排序:
Select * From TableName Order By CustomerName Collate Chinese_PRC_Stroke_ci_as //从少到多

2.数据库加密:
select encrypt(‘原始密码‘)
select pwdencrypt(‘原始密码‘)
select pwdcompare(‘原始密码‘,’加密后密码‘) = 1–相同;否则不相同 encrypt(‘原始密码‘)
select pwdencrypt(‘原始密码‘)
select pwdcompare(‘原始密码‘,’加密后密码‘) = 1–相同;否则不相同

3.取回表中字段:
declare @list varchar(1000),
@sql nvarchar(1000)
select @list=@list+‘,’+b.name from sysobjects a,syscolumns b where a.id=b.id and a.name=‘表A’
set @sql=‘select ‘+right(@list,len(@list)-1)+‘ from 表A‘
exec (@sql)

4.查看硬盘分区:
EXEC master..xp_fixeddrives

5.比较A,B表是否相等:
if (select checksum_agg(binary_checksum(*)) from A)
=
(select checksum_agg(binary_checksum(*)) from B)
print ‘相等‘
else
print ‘不相等‘

6.杀掉所有的事件探察器进程:
DECLARE hcforeach CURSOR GLOBAL FOR SELECT ‘kill ‘+RTRIM(spid) FROM master.dbo.sysprocesses
WHERE program_name IN(‘SQL profiler’,N’SQL 事件探查器‘)
EXEC sp_msforeach_worker ‘?7.记录搜索:
开头到N条记录
Select Top N * From 表
——————————-
N到M条记录(要有主索引ID)
Select Top M-N * From 表 Where ID in (Select Top M ID From 表) Order by ID Desc
———————————-
N到结尾记录
Select Top N * From 表 Order by ID Desc
案例
例如1:一张表有一万多条记录,表的第一个字段 RecID 是自增长字段, 写一个SQL语句, 找出表的第31到第40个记录。

select top 10 recid from A where recid notin(select top 30 recid from A)

分析:如果这样写会产生某些问题,如果recid在表中存在逻辑索引。

select top 10 recid from A where……是从索引中查找,而后面的select top 30 recid from A则在数据表中查找,这样由于索引中的顺序有可能和数据表中的不一致,这样就导致查询到的不是本来的欲得到的数据。

解决方案

1,用order by select top 30 recid from A order by ricid 如果该字段不是自增长,就会出现问题

2,在那个子查询中也加条件:select top 30 recid from A where recid>-1

例2:查询表中的最后以条记录,并不知道这个表共有多少数据,以及表结构。
set @s = ‘select top 1 * from Twhere pid not in (select top ‘ + str(@count-1) + ‘ pidfrom T)’

print @sexecsp_executesql@s

9:获取当前数据库中的所有用户表
select Name from sysobjects where xtype=’u’ and status>=0

10:获取某一个表的所有字段
select name from syscolumns where id=object_id(‘表名‘)

select name from syscolumns where id in (select id from sysobjects where type = ‘u’ and name = ‘表名‘)

两种方式的效果相同

11:查看与某一个表相关的视图、存储过程、函数
select a.* from sysobjects a, syscomments b where a.id = b.id and b.text like ‘%表名%12:查看当前数据库中所有存储过程
select name as 存储过程名称 from sysobjects where xtype=’P’

13:查询用户创建的所有数据库
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 <> 0×01

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

15:不同服务器数据库之间的数据操作

–创建链接服务器

exec sp_addlinkedserver’ITSV ‘, ‘ ‘, ‘SQLOLEDB ‘, ‘远程服务器名或ip地址 ‘

exec sp_addlinkedsrvlogin’ITSV ‘, ‘false ‘,null, ‘用户名 ‘, ‘密码 ‘

–查询示例

select * from ITSV.数据库名.dbo.表名

–导入示例

select * into 表 from ITSV.数据库名.dbo.表名

–以后不再使用时删除链接服务器

exec sp_dropserver’ITSV ‘, ‘droplogins ‘

–连接远程/局域网数据(openrowset/openquery/opendatasource)
–1、openrowset

–查询示例

select * from openrowset( ‘SQLOLEDB ‘, ‘sql服务器名 ‘; ‘用户名 ‘; ‘密码 ‘,数据库名.dbo.表名)

–生成本地表

select * into 表 from openrowset( ‘SQLOLEDB ‘, ‘sql服务器名 ‘; ‘用户名 ‘; ‘密码 ‘,数据库名.dbo.表名)

–把本地表导入远程表
insert openrowset( ‘SQLOLEDB ‘, ‘sql服务器名 ‘; ‘用户名 ‘; ‘密码 ‘,数据库名.dbo.表名)

select *from 本地表

–更新本地表

update b

set b.列A=a.列A

from openrowset( ‘SQLOLEDB ‘, ‘sql服务器名 ‘; ‘用户名 ‘; ‘密码 ‘,数据库名.dbo.表名)as a inner join 本地表 b

on a.column1=b.column1

–openquery用法需要创建一个连接

--首先创建一个连接创建链接服务器

exec sp_addlinkedserver’ITSV ‘, ‘ ‘, ‘SQLOLEDB ‘, ‘远程服务器名或ip地址 ‘

–查询

select *

FROM openquery(ITSV,’SELECT *FROM 数据库.dbo.表名 ‘)

–把本地表导入远程表

insert openquery(ITSV,’SELECT *FROM 数据库.dbo.表名 ‘)

select * from 本地表

–更新本地表

update b

set b.列B=a.列B

FROM openquery(ITSV,’SELECT * FROM 数据库.dbo.表名 ‘) as a

inner join 本地表 b on a.列A=b.列A

–3、opendatasource/openrowset
SELECT*

FROMopendatasource( ‘SQLOLEDB ‘,’Data Source=ip/ServerName;User ID=登陆名;Password=密码 ‘ ).test.dbo.roy_ta

–把本地表导入远程表

insert opendatasource( ‘SQLOLEDB ‘,’Data Source=ip/ServerName;User ID=登陆名;Password=密码 ‘).数据库.dbo.表名

select * from 本地表


SQL Server基本函数

SQL Server基本函数

1.字符串函数 长度与分析用

1,datalength(Char_expr) 返回字符串包含字符数,但不包含后面的空格
2,substring(expression,start,length) 取子串,字符串的下标是从“1”,start为起始位置,length为字符串长度,实际应用中以len(expression)取得其长度
3,right(char_expr,int_expr) 返回字符串右边第int_expr个字符,还用left于之相反
4,isnull( check_expression , replacement_value )如果check_expression為空,則返回replacement_value的值,不為空,就返回check_expression字符操作类

5,Sp_addtype自定義數據類型
例如:EXEC sp_addtype birthday, datetime, NULL




? 2015 内存溢出

其实、这些语句,如果需要想不起来,就看一下,很方便的。

数据库操作----找了MySQL和SQL Sever两个的基础语句