數據庫操做----找了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的語法,其實基本上差很少,這兩天我所用到,大概也就一個遞增、一個級聯不一樣mysql

1、基礎

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’

2、提高
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

3、技巧

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 內存溢出

其實、這些語句,若是須要想不起來,就看一下,很方便的。sql

相關文章
相關標籤/搜索