在SQLPLUS下,實現中-英字符集轉換
alter session set nls_language='AMERICAN';
alter session set nls_language='SIMPLIFIED CHINESE';
主要知識點:java
1、有關表的操做sql
建表數據庫
create table test as select * from dept; --從已知表複製數據和結構
create table test as select * from dept where 1=2; --從已知表複製結構但不包括數據
2)插入數據:
insert into test select * from dept;session
2、運算符oracle
算術運算符:+ - * / 能夠在select 語句中使用
鏈接運算符:|| select deptno|| dname from dept;
比較運算符:> >= = != < <= like between is null in
邏輯運算符:not and or
集合運算符: intersect ,union, union all, minus
要求:對應集合的列數和數據類型相同
查詢中不能包含long 列
列的標籤是第一個集合的標籤
使用order by時,必須使用位置序號,不能使用列名
例:集合運算符的使用:
intersect ,union, union all, minus
select * from emp intersect select * from emp where deptno=10 ;
select * from emp minus select * from emp where deptno=10;
select * from emp where deptno=10 union select * from emp where deptno in (10,20); --不包括重複行
select * from emp where deptno=10 union all select * from emp where deptno in (10,20); --包括重複行 函數
三,經常使用 ORACLE 函數oop
sysdate爲系統日期 dual爲虛表測試
一)日期函數[重點掌握前四個日期函數]
1,add_months[返回日期加(減)指定月份後(前)的日期]
select sysdate S1,add_months(sysdate,10) S2,
add_months(sysdate,5) S3 from dual;
2,last_day [返回該月最後一天的日期]
select last_day(sysdate) from dual;
3,months_between[返回日期之間的月份數]
select sysdate S1, months_between('1-4月-04',sysdate) S2,
months_between('1-4月-04','1-2月-04') S3 from dual
4,next_day(d,day): 返回下個星期的日期,day爲1-7或星期日-星期六,1表示星期日
select sysdate S1,next_day(sysdate,1) S2,
next_day(sysdate,'星期日') S3 FROM DUAL
5,round[舍入到最接近的日期](day:舍入到最接近的星期日)
select sysdate S1,
round(sysdate) S2 ,
round(sysdate,'year') YEAR,
round(sysdate,'month') MONTH ,
round(sysdate,'day') DAY from dual
6,trunc[截斷到最接近的日期]
select sysdate S1,
trunc(sysdate) S2,
trunc(sysdate,'year') YEAR,
trunc(sysdate,'month') MONTH ,
trunc(sysdate,'day') DAY from dual
7,返回日期列表中最晚日期
select greatest('01-1月-04','04-1月-04','10-2月-04') from dualui
二)字符函數(可用於字面字符或數據庫列)
1,字符串截取
select substr('abcdef',1,3) from dual
2,查找子串位置
select instr('abcfdgfdhd','fd') from dual
3,字符串鏈接
select 'HELLO'||'hello world' from dual;
4, 1)去掉字符串中的空格
select ltrim(' abc') s1,
rtrim('zhang ') s2,
trim(' zhang ') s3 from dual
2)去掉前導和後綴
select trim(leading 9 from 9998767999) s1,
trim(trailing 9 from 9998767999) s2,
trim(9 from 9998767999) s3 from dual;
5,返回字符串首字母的Ascii值
select ascii('a') from dual
6,返回ascii值對應的字母
select chr(97) from dual
7,計算字符串長度
select length('abcdef') from dual
8,initcap(首字母變大寫) ,lower(變小寫),upper(變大寫)
select lower('ABC') s1,
upper('def') s2,
initcap('efg') s3 from dual;
9,Replace
select replace('abc','b','xy') from dual;
10,translate
select translate('abc','b','xx') from dual; -- x是1位
11,lpad [左添充] rpad [右填充](用於控制輸出格式)
select lpad('func',15,'=') s1, rpad('func',15,'-') s2 from dual;
select lpad(dname,14,'=') from dept;
12, decode[實現if ..then 邏輯]
select deptno,decode(deptno,10,'1',20,'2',30,'3','其餘') from dept;spa
三)數字函數
1,取整函數(ceil 向上取整,floor 向下取整)
select ceil(66.6) N1,floor(66.6) N2 from dual;
2, 取冪(power) 和 求平方根(sqrt)
select power(3,2) N1,sqrt(9) N2 from dual;
3,求餘
select mod(9,5) from dual;
4,返回固定小數位數 (round:四捨五入,trunc:直接截斷)
select round(66.667,2) N1,trunc(66.667,2) N2 from dual;
5,返回值的符號(正數返回爲1,負數爲-1)
select sign(-32),sign(293) from dual;
四)轉換函數
1,to_char()[將日期和數字類型轉換成字符類型]
1) select to_char(sysdate) s1,
to_char(sysdate,'yyyy-mm-dd') s2,
to_char(sysdate,'yyyy') s3,
to_char(sysdate,'yyyy-mm-dd hh12:mi:ss') s4,
to_char(sysdate, 'hh24:mi:ss') s5,
to_char(sysdate,'DAY') s6 from dual;
2) select sal,to_char(sal,'$99999') n1,to_char(sal,'$99,999') n2 from emp
2, to_date()[將字符類型轉換爲日期類型]
insert into emp(empno,hiredate) values(8000,to_date('2004-10-10','yyyy-mm-dd'));
3, to_number() 轉換爲數字類型
select to_number(to_char(sysdate,'hh12')) from dual; //以數字顯示的小時數
五)其餘函數
user:
返回登陸的用戶名稱
select user from dual;
vsize:
返回表達式所需的字節數
select vsize('HELLO') from dual;
nvl(ex1,ex2):
ex1值爲空則返回ex2,不然返回該值自己ex1(經常使用)
例:若是僱員沒有佣金,將顯示0,不然顯示佣金
select comm,nvl(comm,0) from emp;
nullif(ex1,ex2):
值相等返空,不然返回第一個值
例:若是工資和佣金相等,則顯示空,不然顯示工資
select nullif(sal,comm),sal,comm from emp;
coalesce:
返回列表中第一個非空表達式
select comm,sal,coalesce(comm,sal,sal*10) from emp;
nvl2(ex1,ex2,ex3) :
若是ex1不爲空,顯示ex2,不然顯示ex3
如:查看有佣金的僱員姓名以及他們的佣金
select nvl2(comm,ename,') as HaveCommName,comm from emp;
六)分組函數
max min avg count sum
1,整個結果集是一個組
1) 求部門30 的最高工資,最低工資,平均工資,總人數,有工做的人數,工種數量及工資總和
select max(ename),max(sal),
min(ename),min(sal),
avg(sal),
count(*) ,count(job),count(distinct(job)) ,
sum(sal) from emp where deptno=30;
2, 帶group by 和 having 的分組
1)按部門分組求最高工資,最低工資,總人數,有工做的人數,工種數量及工資總和
select deptno, max(ename),max(sal),
min(ename),min(sal),
avg(sal),
count(*) ,count(job),count(distinct(job)) ,
sum(sal) from emp group by deptno;
2)部門30的最高工資,最低工資,總人數,有工做的人數,工種數量及工資總和
select deptno, max(ename),max(sal),
min(ename),min(sal),
avg(sal),
count(*) ,count(job),count(distinct(job)) ,
sum(sal) from emp group by deptno having deptno=30;
3, stddev 返回一組值的標準誤差
select deptno,stddev(sal) from emp group by deptno;
variance 返回一組值的方差差
select deptno,variance(sal) from emp group by deptno;
4, 帶有rollup和cube操做符的Group By
rollup 按分組的第一個列進行統計和最後的小計
cube 按分組的全部列的進行統計和最後的小計
select deptno,job ,sum(sal) from emp group by deptno,job;
select deptno,job ,sum(sal) from emp group by rollup(deptno,job);
cube 產生組內全部列的統計和最後的小計
select deptno,job ,sum(sal) from emp group by cube(deptno,job);
參見:http://www.javaeye.com/topic/201757
7、臨時表
只在會話期間或在事務處理期間存在的表.
臨時表在插入數據時,動態分配空間
create global temporary table temp_dept
(dno number,
dname varchar2(10))
on commit delete rows;
insert into temp_dept values(10,'ABC');
commit;
select * from temp_dept; --無數據顯示,數據自動清除
on commit preserve rows:在會話期間表一直能夠存在(保留數據)
on commit delete rows:事務結束清除數據(在事務結束時自動刪除表的數據)
========================== 鏈接操做 ================================
例若有A,B兩張表:
A表 B表
a b c d
1 0 4 7
2 9 1 5
select * from A,B where A.a = B.c
等同於
select * from A join B on A.a = B.c
結果:
a b c d
1 0 1 5
左鏈接:
select * from A,B where A.a = B.c(+)
等同於
select * from A left join B on A.a = B.c
即以A表查詢爲主,附帶查詢出知足A.a = B.c條件的B表中的結果
結果:
a b c d
1 0 1 5
2 9
右鏈接:
select * from A,B where A.a(+) = B.c
等同於
select * from A right join B on A.a = B.c
此查詢爲左鏈接,即以A表查詢爲主,附帶查詢出知足A.a = B.c條件的B表中的結果
結果:
c d a b
1 5 1 0
4 7
===============================================================
===================== oracle 函數 ===============================
DECODE:
decode(條件,值1,翻譯值1,值2,翻譯值2,...值n,翻譯值n,缺省值)
A表
a b c
1 3 0
3 2 9
1 0 5
3 7 7
5 5 9
select decode(A.a,1,4,3,8),A.b,A.c form A
意思:若是A.a的值爲1,則將A.a的值查詢爲4,若是A.a的值爲3,則將A.a的值查詢爲8
結果:
a b c
4 3 0
8 2 9
4 0 5
8 7 7
5 5 9
select decode(A.a,1,4,8),A.b,A.c form A
意思:若是A.a的值爲1,則將A.a的值查詢爲4,不然A.a的值查詢爲8
結果:
a b c
4 3 0
8 2 9
4 0 5
8 7 7
8 5 9
select decode(A.a,1,4,3,8,7),A.b,A.c form A
意思:若是A.a的值爲1,則將A.a的值查詢爲4,若是A.a的值爲3,則將A.a的值查詢爲8,不然查詢爲7
結果:
a b c
4 3 0
8 2 9
4 0 5
8 7 7
7 5 9
===============================================================
==========================SEQUENCE=====================================
SEQUENCE: CREATE SEQUENCE LOCATIONS_SEQ
INCREMENT BY 1
START WITH 1
MAXVALUE 9900
MINVALUE 1
SELECT LOCATIONS_SEQ.currval FROM DUAL ;
SELECT LOCATIONS_SEQ.nextval FROM DUAL ;
============================SEQUENCE===================================
============================函數===================================
日期函數:
add_months(d,n) 日期d加n個月
last_day(d) 包含d的月份的最後一天的日期
month_between(d,e) 日期d與e之間的月份數,e先於d
new_time(d,a,b) a時區的日期和時間d在b時區的日期和時間
next_day(d,day) 比日期d晚,由day指定的周幾的日期
sysdate 當前的系統日期和時間
greatest(d1,d2,...dn) 給出的日期列表中最後的日期
least(d1,k2,...dn) 給出的日期列表中最先的日期
to_char(d [,fmt]) 日期d按fmt指定的格式轉變成字符串
to_date(st [,fmt]) 字符串st按fmt指定的格式轉成日期值,若fmt忽略,st要用缺省格式
round(d [,fmt]) 日期d按fmt指定格式舍入到最近的日期
trunc(d [,fmt]) 日期d按fmt指定格式截斷到最近的日期
分組函數:
avg([distinct/all] n) 列n的平均值
count([all] *) 返回查詢範圍內的行數包括重複值和空值
count([distinct/all] n) 非空值的行數
max([distinct/all] n) 該列或表達式的最大值
min([distinct/all] n) 該列或表達式的最小值
stdev([distinct/all] n) 該列或表達式的標準誤差,忽略空值
sum([distinct/all] n) 該列或表達式的總和
variance([distinct/all] n) 該列或表達式的方差,忽略空值
數值函數:
abs(m) m的絕對值
mod(m,n) m被n除後的餘數
power(m,n) m的n次方
round(m[,n]) m四捨五入至小數點後n位的值(n缺省爲0)
trunc(m[,n]) m截斷n位小數位的值(n缺省爲0)
字符函數:
initcap(st) 返回st將每一個單詞的首字母大寫,全部其餘字母小寫
lower(st) 返回st將每一個單詞的字母所有小寫
upper(st) 返回st將每一個單詞的字母所有大寫
concat(st1,st2) 返回st爲st2接st1的末尾(可用操做符"||")
lpad(st1,n[,st2]) 返回右對齊的st,st爲在st1的左邊用st2填充直至長度爲n,st2的缺省爲空格
rpad(st1,n[,st2]) 返回左對齊的st,st爲在st1的右邊用st2填充直至長度爲n,st2的缺省爲空格
ltrim(st[,set]) 返回st,st爲從左邊刪除set中字符直到第一個不是set中的字符。缺省時,指的是空格
rtrim(st[,set]) 返回st,st爲從右邊刪除set中字符直到第一個不是set中的字符。缺省時,指的是空格
replace(st,search_st[,replace_st]) 將每次在st中出現的search_st用replace_st替換,返回一個st。缺省時,
刪除search_st
substr(st,m[,n]) n=返回st串的子串,從m位置開始,取n個字符長。缺省時,一直返回到st末端
length(st) 數值,返回st中的字符數
instr(st1,st2[,m[,n]]) 數值,返回st1從第m字符開始,st2第n次出現的位置,m及n的缺省值爲1
關於樹形結構表的遞歸查詢:
Start with ~~ connect by prior ~~~~
CREATE TABLE TBL_TEST
(
ID NUMBER,
NAME VARCHAR2(100 BYTE),
PID NUMBER
);
INSERT INTO TBL_TEST(ID,NAME,PID) VALUES('1','10','0');
INSERT INTO TBL_TEST(ID,NAME,PID) VALUES('2','11','1');
INSERT INTO TBL_TEST(ID,NAME,PID) VALUES('3','20','0');
INSERT INTO TBL_TEST(ID,NAME,PID) VALUES('4','12','1');
INSERT INTO TBL_TEST(ID,NAME,PID) VALUES('5','121','2');
1,向下查詢
select * from TBL_TEST t
start with id=5
connect by prior id = pid
2,向上查詢
select * from TBL_TEST
start with id=5
connect by prior pid = id
oracle 所特有的 函數
decode
DECODE函數是ORACLE PL/SQL是功能強大的函數之一,目前還只有ORACLE公司的SQL提供了此函數,其餘數據庫廠商的SQL實現尚未此功能。DECODE有什麼用途 呢? 先構造一個例子,假設咱們想給智星職員加工資,其標準是:工資在8000元如下的將加20%;工資在8000元以上的加15%,一般的作法是,先選出記錄 中的工資字段值? select salary into var-salary from employee,而後對變量var-salary用if-then-else或choose case之類的流控制語句進行判斷。 若是用DECODE函數,那麼咱們就能夠把這些流控制語句省略,經過SQL語句就能夠直接完成。以下:select decode(sign(salary - 8000),>0,salary*1.15,<0,salary*1.2,salary) from employee 是否是很簡潔? DECODE的語法:DECODE(value,if1,then1,if2,then2,if3,then3,...,else),表示若是value 等於if1時,DECODE函數的結果返回then1,...,若是不等於任何一個if值,則返回else。初看一下,DECODE 只能作等於測試,但剛纔也看到了,咱們經過一些函數或計算替代value,是可使DECODE函數具有大於、小於或等於功能。
n Select decode(值1,值2,返回值1,返回值2) from table;
n Select (case when condition1 then 返回值1 when condition2 then 返回值2 end) from table;
n Decode能夠與caise ..when .. End相互轉換,相對case .. When .. End更好用.
一、說明:建立數據庫
CREATE DATABASE database-name
二、說明:刪除數據庫
drop database dbname
三、說明:備份sql server
--- 建立 備份數據的 device
USE master
EXEC sp_addumpdevice 'disk', 'testBack', 'c:\mssql7backup\MyNwind_1.dat'
--- 開始 備份
BACKUP DATABASE pubs TO testBack
四、說明:建立新表
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
五、說明:刪除新表
drop table tabname
六、說明:增長一個列
Alter table tabname add column col type
注:列增長後將不能刪除。DB2中列加上後數據類型也不能改變,惟一能改變的是增長varchar類型的長度。
七、說明:添加主鍵: Alter table tabname add primary key(col)
說明:刪除主鍵: Alter table tabname drop primary key(col)
八、說明:建立索引:create [unique] index idxname on tabname(col….)
刪除索引:drop index idxname
注:索引是不可更改的,想更改必須刪除從新建。
九、說明:建立視圖:create view viewname as select statement
刪除視圖:drop view viewname
十、說明:幾個簡單的基本的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
十一、說明:幾個高級查詢運算詞
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),不消除重複行。
注:使用運算詞的幾個查詢結果行必須是一致的。
十二、說明:使用外鏈接
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 outer join:
全外鏈接:不只包括符號鏈接表的匹配行,還包括兩個鏈接表中的全部記錄。
2、提高
一、說明:複製表(只複製結構,源表名:a 新表名:b) (Access可用)
法一:select * into b from a where 1<>1
法二:select top 0 * into b from a
二、說明:拷貝表(拷貝數據,源表名:a 目標表名:b) (Access可用)
insert into b(a, b, c) select d,e,f from b;
三、說明:跨數據庫之間表的拷貝(具體數據使用絕對路徑) (Access可用)
insert into b(a, b, c) select d,e,f from b in ‘具體數據庫’ where 條件
例子:..from b in '"&Server.MapPath(".")&"\data.mdb" &"' where..
四、說明:子查詢(表名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)
五、說明:顯示文章、提交人和最後回覆時間
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)
select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c
七、說明:在線視圖查詢(表名1:a )
select * from (SELECT a,b,c FROM a) T where t.a > 1;
八、說明: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
九、說明:in 的使用方法
select * from table1 where a [not] in (‘值1’,’值2’,’值4’,’值6’)
十、說明:兩張關聯表,刪除主表中已經在副表中沒有的信息
delete from table1 where not exists ( select * from table2 where table1.field1=table2.field1 )
十一、說明:四表聯查問題:
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 .....
十二、說明:日程安排提早五分鐘提醒
SQL: select * from 日程安排 where datediff('minute',f開始時間,getdate())>5
1三、說明:一條sql 語句搞定數據庫分頁
select top 10 b.* from (select top 20 主鍵字段,排序字段 from 表名 order by 排序字段 desc) a,表名 b where b.主鍵字段 = a.主鍵字段 order by a.排序字段
1四、說明:前10條記錄
select top 10 * form table1 where 範圍
1五、說明:選擇在每一組b值相同的數據中對應的a最大的記錄的全部信息(相似這樣的用法能夠用於論壇每個月排行榜,每個月熱銷產品分析,按科目成績排名,等等.)
select a,b,c from tablename ta where a=(select max(a) from tablename tb where tb.b=ta.b)
1六、說明:包括全部在 TableA 中但不在 TableB和TableC 中的行並消除全部重複行而派生出一個結果表
(select a from tableA ) except (select a from tableB) except (select a from tableC)
1七、說明:隨機取出10條數據
select top 10 * from tablename order by newid()
1八、說明:隨機選擇記錄
select newid()
1九、說明:刪除重複記錄
Delete from tablename where id not in (select max(id) from tablename group by col1,col2,...)
20、說明:列出數據庫裏全部的表名
select name from sysobjects where type='U'
2一、說明:列出表裏的全部的
select name from syscolumns where id=object_id('TableName')
2二、說明:列示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
2三、說明:初始化表table1
TRUNCATE TABLE table1
2四、說明:選擇從10到15的記錄
select top 5 * from (select top 15 * from table order by id asc) table_別名 order by id desc
3、技巧
一、1=1,1=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
二、收縮數據庫
--重建索引
DBCC REINDEX
DBCC INDEXDEFRAG
--收縮數據和日誌
DBCC SHRINKDB
DBCC SHRINKFILE
三、壓縮數據庫
dbcc shrinkdatabase(dbname)
四、轉移數據庫給新用戶以已存在用戶權限
exec sp_change_users_login 'update_one','newname','oldname'
go
五、檢查備份集
RESTORE VERIFYONLY from disk='E:\dvbbs.bak'
六、修復數據庫
ALTER DATABASE [dvbbs] SET SINGLE_USER
GO
DBCC CHECKDB('dvbbs',repair_allow_data_loss) WITH TABLOCK
GO
ALTER DATABASE [dvbbs] SET MULTI_USER
GO
七、日誌清除
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
八、說明:更改某個表
exec sp_changeobjectowner 'tablename','dbo'
九、存儲更改所有表
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
十、SQL SERVER中直接循環寫入數據
declare @i int
set @i=1
while @i<30
begin
insert into test (userid) values(@i)
set @i=@i+1
end
十一、一些排名函數
(可參見:http://blog.csdn.net/zzuyongp/archive/2009/05/10/4164891.aspx)
row_number() 最經常使用——出現重複的只取第一個
rank() 兩個名次同樣的,下一條數據自動跳過
dense_rank() 兩個名次不同的,下一條數據不跳過
一些混合用法:
聚合函數/排序函數+ Over(partition by column order by column)
(可參見:http://blog.csdn.net/cnham/archive/2009/08/30/4500928.aspx)
1,
select decode(sign(numb-6),-1,numb,6) numb,decode(sign(numb-6),-1,xingshi,'其餘') xingshi, sum(amount) from
(select xingshi,amount, row_number() over(order by amount desc) numb from
(select substr(t.name,1,1) xingshi, count(1) amount from pub_user t
where substr(t.name,1,1) not between '0' and '9' and substr(t.name,1,1) not between 'a' and 'z'
group by substr(t.name,1,1) order by amount desc )
) group by decode(sign(numb-6),-1,numb,6),decode(sign(numb-6),-1,xingshi,'其餘')
或者:
select t.key taskType,sum(rn) countNum,t.key_rn from
(select (case when key <=5 then xingshi
else '其餘' end) key,
(case when key <=5 then key
else 6 end) key_rn,rn
from (select row_number() over(
order by rn desc) key,rn,xingshi
from (
select t.xingshi,count(1) rn
from (select substr(t.name,1,1) xingshi,
t.user_id from pub_user t) t
where xingshi not between
'a' and 'z' and xingshi
not between '0' and '9'
group by t.xingshi))) t
group by t.key,t.key_rn order by t.key_rn;
2,
select * from ( select rank() over(partition by classroom order by grade desc)mm ,name,grade,classroom from grade_class) t where t.grade>90
3,
select avg(grade) AS 平均分,t.classroom from grade_class t group by t.classroom having avg(grade)>94