蜀山趙氏SQL手冊

現在做IT的各個要求是全能,這個是百分之百不現實的。如何能夠在最短的時間內,找到自己想要的東西。其實最好的是自己將以前看過的東西進行一個總結。現在我貼出我很早以前寫的SQL幫助手冊。都是很基礎的東西,主要是格式。

希望對於那些業餘要搞搞SQLSERVER的朋友一些幫助吧。

-------------------------------------------------------------------------------------------------
在SQL語句中 CASE 與高級語言SWITCH  適用一個條件判斷有多個值的情況分別執行不同操作

case... when

commit  結束當前事務

在裏面還用到了 comment on 添加註釋
comment on table 添加表註釋

comment on column 添加列註釋

格式如下
comment on table 表名 is '註釋';

主鍵primary key

添加格式
insert into 表名(字段名) values ('插入內容'),
添加主鍵
insert into 表名 primary key not null

添加主鍵格式2
add primary key (表名)

identity屬性
作用 創建一個標識列
identity [(seed,increment)]  默認狀態爲identity(1,1)
--seed的作用是裝在到表中第一行所使用的值
--increment 作爲增量值

select max(字段名) from 表名
--判斷字段名組裏字段最大的值

升序和降序排列:

order by ...desc

降序排列


order by ...asc

升序排列

實例 :

select * from  表名   order by 字段 desc   從大到小排列

select * from 表名  order by 字段 asc 從小到大排列

繼續實例
select 列名 from 表名 order by 字段 desc

 

alter 修改

alter table 表名 add 字段 date--類型

alter table 表名

刪除字段

delete  from 表名 where 條件

各種計算語句

select avg(字段名),max(字段名),min(字段名),sum(字段名),max(字段名)-min(字段名)
--avg 求平均數    max 最大值   min 最小值  sum 求和 max-min 求值之間


update語句

update 表名 set 字段名 where 字段名=‘ ’

求最大值max()
實例求年齡最大的員工姓名

selcet name from person where age=(select age from person where max(age))3

消息 4145,級別 15,狀態 1,第 2 行
在應使用條件的上下文(在 ')' 附近)中指定了非布爾類型的表達式。  有錯

as 別名

格式:
select 列名(s)  from 表名  as 別名      表的語法

select 列名(s)  as 別名    from 表名    列的語法

實例:

select 別名.orderID, 別名.lastname,別名.fristname from 表名 as 別名 where 別名.orderID='字段名' where 別名.lastname='字段名'
 
--作用在於簡化編寫過程。。。。。。


注意事項:
在使用alter table 表名 add 字段名      --字段名後面不能使用 not null  在添加新字段的時候必須使字段可以爲空設置

 

添加個刪除主鍵名

alter table book_2 add  constraint 約束名 primary key(列名)

--constraint 約束     意思就是添加約束名及主鍵      

alter table book_2 drop constraint 約束名

--刪除約束名  取消主鍵約束


查詢用暱稱顯示列名

select 暱稱=列名 from  表名

 

SELECT ColumnList FROM TableA inner join tableB on linkList

用於執行TableA和TableB之間的嚴格約束關係,即內聯關係,就是說linkList中提出的等於的約束關係,是左右對等的 比如

a.code=b.code,那麼a中的code必須在b中存在並且等於

如果是Left join,那麼 a.code=b.code,就是a.code未必存在於b中,如果存在,則執行對等關係

 

inner join內聯

left join左聯

right join右聯

cross join交叉聯

full join

on 後面跟着條件

不重複顯示查詢結果語句

union 和SELECT DISTINCT Date

實例:

SQL語句1  union SQL語句2

如果一個語句中存在重複信息則使用select distinct data

實例:

select distinct 列名 from 表名


使用 full join 實例

select 字段名 from 表名 full join 表名2 on 表名.字段名=表名2.字段名2

 

top語句

實例:

select top 排名 * from 表名

按照百分比例取條數

select top 數字 percent * from 表名

--percent 是百分數

LIKE與[]的使用實例

select 列名 from 表名 where 列名 like '[開頭字母或數字]%'

以指定字母或數字開頭的列名輸出

select 列名 from 表名 where 列名 like '%[開頭字母或數字]%'

包含有指定字母或數字的列名輸出


select 列名 from 表名 where 列名 like '[!/^開頭字母或數字]%'

不包含指定字母或數字的列名輸出

 


in操作符的應用

實例說明

select * from 表名 where 列名 in ('列名包含字段')
輸出結果 爲制定包含字段的列名全部信息
貌似和select 包含字段的列名 from 表名 相等   在未知情況下用in解決

 


between範圍語句

實例說明

select * from 表名 where 列名 between '範圍1' and '範圍2'
由於數據庫處理差異不同可能存在 包含範圍1 不包含 範圍2  包含範圍1和2   不包含範圍1和2 的情況出現

inner join內聯實例

select 別名.列名  from 表名 as 別名
inner join 表名2 as 別名
on 別名.主鍵名=別名.主鍵名2
group by 別名.列名

 


備份附件 into / into ... in

實例

select 列名/*
into 新表名
from 舊錶名

select 列名/* 
into 數據庫名.dbo.新表名
from 數據庫名.dbo.舊錶名
--將舊錶中的字段信息調入另一個數據庫中並創建新表

SELECT 表名.列名,表名.列名
INTO 新表名
FROM 舊錶名
INNER JOIN 列名
ON 表名.主鍵名=表名2.主鍵名
--爲新表添加舊錶中的特定信息

date類型

integer(size)
int(size)
smallint(size)
tinyint(size)
 僅容納整數。在括號內規定數字的最大位數。
decimal(size,d)
numeric(size,d)
 容納帶有小數的數字。

"size" 規定數字的最大位數。"d" 規定小數點右側的最大位數。
 
char(size) 容納固定長度的字符串(可容納字母、數字以及特殊字符)。

在括號中規定字符串的長度。
 
varchar(size) 容納可變長度的字符串(可容納字母、數字以及特殊的字符)。

在括號中規定字符串的最大長度。
 
date(yyyymmdd) 容納日期。


not null 如果不想字段中插入數值就無法更新和插入新數據


unique 添加約束  每個表可以添加多條約束  但是 主鍵  primary key 只能增加一條 

 


刪除約束

實例:

alter 表名 drop constraint 列名

 

外鍵設置


瞭解外鍵作用:
1.  FOREIGN KEY 約束用於預防破壞表之間連接的動作。

2.  FOREIGN KEY 約束也能防止非法數據插入外鍵列,因爲它必須是它指向的那個表中的值之一。

實例:

CREATE TABLE 表名
(
列名 int NOT NULL PRIMARY KEY,
列名 int NOT NULL,
列名 int FOREIGN KEY REFERENCES 表名1(主鍵名)
)

 

check 約束
對錶和列進行約束  約束範圍是限定列的值

實例:

CREATE TABLE 表名
(
列名 int NOT NULL check (列名>0),
列名 int NOT NULL,
列名 int NOT NULL,
)
--check>0表示列名值必須大於零才能被輸入


CREATE TABLE 表名
(
列名 date NOT NULL,
列名 date NOT NULL,
列名 date,
列名 date,
列名 date,
CONSTRAINT 約束名 CHECK (約束條件)
)
--命名約束和 定義多個約束

 

alter table 表名 add check (列名條件)
--爲存在的列名添加check  約束

 

alter table 表名 add constraint 約束名 check (列名條件)
--添加約束名和約束條件

 


default約束

說明:default 約束用於向列中插入默認值,如果沒有其他規定則向新紀錄插入默認值

getdate()參數  可以用於插入系統值

實例
orderdate date default getdate()

 


index索引

創建一個索引
實例:
create index 索引名
on 表名(列名)

刪除索引

drop index 表名.索引名

顯示與特定時間所查天數
Select datediff (day,getdate(),'2008-08-08')

建立check約束

格式:alter table 表名 add constraint 約束名 check(列名 約束條件)

實例:alter table book_2 add constraint aaaa check(b_sn between 1 and 100)


identity關鍵字 執行auto-increment命令

用法
create table 表名
(
    列名 date primary key identity,
    列名 date not null,
)

--默認地,IDENTITY 的開始值是 1,每條新紀錄遞增 1。

要規定 "P_Id" 列以 20 起始且遞增 10,請把 identity 改爲 IDENTITY(20,10)。

 


date函數

GETDATE() 返回當前日期和時間

DATEPART() 返回日期/時間的單獨部分

DATEADD() 在日期中添加或減去指定的時間間隔

DATEDIFF() 返回兩個日期之間的時間

CONVERT() 用不同的格式顯示日期/時間

SQL Server 使用下列數據類型在數據庫中存儲日期或日期/時間值:

DATE - 格式 YYYY-MM-DD
DATETIME - 格式: YYYY-MM-DD HH:MM:SS
SMALLDATETIME - 格式: YYYY-MM-DD HH:MM:SS
TIMESTAMP - 格式: 唯一的數字


NULL函數

我們可以當它爲佔位符


在執行的時候我們使用IS NULL

實例:

select 列名
from 表名
where 列名 is null / where 列名 not is null


null在計算方面

實例:

SELECT 列名,含整型字段的列名*(含整型字段的列名2 +ISNULL(含整型字段的列名3,0))
FROM Products

--這裏isnull的作用是將 爲空的字段 以0表示 方便計算

 

 

數據類型
Character 字符串:
數據類型 描述 存儲
char(n) 固定長度的字符串。最多 8,000 個字符。 n
varchar(n) 可變長度的字符串。最多 8,000 個字符。  
varchar(max) 可變長度的字符串。最多 1,073,741,824 個字符。  
text 可變長度的字符串。最多 2GB 字符數據。  

Unicode 字符串:
數據類型 描述 存儲
nchar(n) 固定長度的 Unicode 數據。最多 4,000 個字符。  
nvarchar(n) 可變長度的 Unicode 數據。最多 4,000 個字符。  
nvarchar(max) 可變長度的 Unicode 數據。最多 536,870,912 個字符。  
ntext 可變長度的 Unicode 數據。最多 2GB 字符數據。  

Binary 類型:
數據類型 描述 存儲
bit 允許 0、1 或 NULL  
binary(n) 固定長度的二進制數據。最多 8,000 字節。  
varbinary(n) 可變長度的二進制數據。最多 8,000 字節。  
varbinary(max) 可變長度的二進制數據。最多 2GB 字節。  
p_w_picpath 可變長度的二進制數據。最多 2GB。  

Number 類型:
數據類型 描述 存儲
tinyint 允許從 0 到 255 的所有數字。 1 字節
smallint 允許從 -32,768 到 32,767 的所有數字。 2 字節
int 允許從 -2,147,483,648 到 2,147,483,647 的所有數字。 4 字節
bigint 允許介於 -9,223,372,036,854,775,808 和 9,223,372,036,854,775,807 之間的所有數字。 8 字節
decimal(p,s) 固定精度和比例的數字。允許從 -10^38 +1 到 10^38 -1 之間的數字。

p 參數指示可以存儲的最大位數(小數點左側和右側)。p 必須是 1 到 38 之間的值。默認是 18。

s 參數指示小數點右側存儲的最大位數。s 必須是 0 到 p 之間的值。默認是 0。
 5-17 字節
numeric(p,s) 固定精度和比例的數字。允許從 -10^38 +1 到 10^38 -1 之間的數字。

p 參數指示可以存儲的最大位數(小數點左側和右側)。p 必須是 1 到 38 之間的值。默認是 18。

s 參數指示小數點右側存儲的最大位數。s 必須是 0 到 p 之間的值。默認是 0。
 5-17 字節
smallmoney 介於 -214,748.3648 和 214,748.3647 之間的貨幣數據。 4 字節
money 介於 -922,337,203,685,477.5808 和 922,337,203,685,477.5807 之間的貨幣數據。 8 字節
float(n) 從 -1.79E + 308 到 1.79E + 308 的浮動精度數字數據。參數 n 指示該字段保存 4 字節還是 8 字節。float(24) 保存 4 字節,而 float(53) 保存 8 字節。n 的默認值是 53。  4 或 8 字節
real 從 -3.40E + 38 到 3.40E + 38 的浮動精度數字數據。 4 字節

Date 類型:
數據類型 描述 存儲
datetime 從 1753 年 1 月 1 日 到 9999 年 12 月 31 日,精度爲 3.33 毫秒。 8 bytes
datetime2 從 1753 年 1 月 1 日 到 9999 年 12 月 31 日,精度爲 100 納秒。 6-8 bytes
smalldatetime 從 1900 年 1 月 1 日 到 2079 年 6 月 6 日,精度爲 1 分鐘。 4 bytes
date 僅存儲日期。從 0001 年 1 月 1 日 到 9999 年 12 月 31 日。 3 bytes
time 僅存儲時間。精度爲 100 納秒。 3-5 bytes
datetimeoffset 與 datetime2 相同,外加時區偏移。 8-10 bytes
timestamp 存儲唯一的數字,每當創建或修改某行時,該數字會更新。timestamp 基於內部時鐘,不對應真實時間。每個表只能有一個 timestamp 變量。  

其他數據類型:
數據類型 描述
sql_variant 存儲最多 8,000 字節不同數據類型的數據,除了 text、ntext 以及 timestamp。
uniqueidentifier 存儲全局標識符 (GUID)。
xml 存儲 XML 格式化數據。最多 2GB。
cursor 存儲對用於數據庫操作的指針的引用。
table 存儲結果集,供稍後處理。


數據庫服務器

DBMS - 數據庫管理系統(Database Management System)
數據庫管理系統是一種可以訪問數據庫中數據的計算機程序。

DBMS 使我們有能力在數據庫中提取、修改或者存貯信息。

不同的 DBMS 提供不同的函數供查詢、提交以及修改數據。
RDBMS - 關係數據庫管理系統(Relational Database Management System)
關係數據庫管理系統 (RDBMS) 也是一種數據庫管理系統,其數據庫是根據數據間的關係來組織和訪問數據的。

20 世紀 70 年代初,IBM 公司發明了 RDBMS。

RDBMS 是 SQL 的基礎,也是所有現代數據庫系統諸如 Oracle、SQL Server、IBM DB2、Sybase、MySQL 以及 Microsoft Access 的基礎。

 

 

AVG的運用
--AVG 平均值

實例:
select avg(列名) from 表名
--求列的平均值

select 列名 from 表名 where 列名>(select AVG(列名) from 表名)
--列出大於平均數的字段名 比如列出年齡大於平均數的 人的姓名

其他的比如MAX和MIN  大家舉一反三

 

count的運用
--count 表中所佔的數列

實例:
select count(列名) from 表名
--指定的列名下字段的列數

select count(列名) from 表名 where 列名='字段名'

 

還有求偶數
%2=0
求奇數
%2=1

select 列名 from 表名 where 列名%2=0


group by 分組
--適合於分與求和差等計算式的常用

實例:select 列名1 sun(列名2) from 表名 group by 列名1
--結果進行分組求和。

分組求和
按照個人習慣寫的 使用having 函數 加在group by後面  做爲合計函數的條件語句
加having實例:
select 列名 sum(列名2)
from 表名
where 列名='字段名'
group by 列名
having sum(列名)>指定數值
--where 不能作爲合計函數條件的時候用having 設置合計函數條件使用

大小寫轉化
ucase()
--這個很簡單 點下就行了
select ucase(列名) as 列名 from 表名
--將列名轉化成大寫

lcase()
--轉化成小寫

select lcase(列名) as 列名 from 表名

 


len()函數
--提取列中字段所佔長度

實例:
select len(列名) as 別名 from 表名

 


getdate()顯示時間語句

實例:
select getdate() 列名 from 表名


知識點: TRUNCATE 刪除表中的所有行,而不記錄單個行刪除操作,不能帶條件
         STATISTICS 顯示磁盤活動量的信息。
         +在程序裏面是連接的意思 比如 ['+tablename+'] 是用來表示字符串

 


    @PageSize int =5
    --頁面大小
    @TotalCount int out
    --總共的列


sp_executesql
執行可以多次重用或動態生成的 Transact-SQL 語句或批處理。Transact-SQL 語句或批處理可以包含嵌入參數。

語法
sp_executesql [@stmt =] stmt
[
    {, [@params =] N'@parameter_name  data_type [,...n]' }
    {, [@param1 =] 'value1' [,...n] }
]

參數
[@stmt =] stmt

包含 Transact-SQL 語句或批處理的 Unicode 字符串,stmt 必須是可以隱式轉換爲 ntext 的 Unicode 常量或變量。不允許使用更復雜的 Unicode 表達式(例如使用 + 運算符串聯兩個字符串)。不允許使用字符常量。如果指定常量,則必須使用 N 作爲前綴。例如,Unicode 常量 N'sp_who' 是有效的,但是字符常量 'sp_who' 則無效。字符串的大小僅受可用數據庫服務器內存限制。


簡單的單表分頁
use zyx
go
SELECT TOP 3 *
FROM
        (
        SELECT ROW_NUMBER() OVER (ORDER BY b_id) AS RowNumber,* FROM book
        ) A
WHERE RowNumber > 3*(2-1)

 


RANK ( ) OVER ( [query_partition_clause] order_by_clause )
DENSE_RANK ( ) OVER ( [query_partition_clause] order_by_clause )
可實現按指定的字段分組排序,對於相同分組字段的結果集進行排序,
其中PARTITION BY 爲分組字段,ORDER BY 指定排序字段

rank,row_number,desc_rank的區別

--rank根據order by的排名會出現並列的現象,在排名順序時出現1,2,3,4,4,6,7,7,9
--desc_rank根據order by的排名會出現並列現象,但是不會不會跳過顯示1,2,2,3,3,4,4
--row_number根據order by的排名不會出現並列現象1,2,3,4,5,6,7

 

實例
use zyp
declare @table table (b_sn varchar(50),b_name varchar(50), b_id int,count int)
insert @table
select b_sn,b_name,b_id,count(b_id) from book_2 as c
group by b_sn,b_name,b_id

select c.b_sn,c.b_name,min(c.b_id)
from
(
select a.b_sn,a.b_name,b.b_id from
(
select b_sn,b_name,max(count) as Cou from @table
group by b_sn,b_name
) as a
inner join @table as b
on a.b_sn=b.b_sn and a.b_name=b.b_name and a.cou=b.count
) as c
group by c.b_sn,c.b_name


--查詢出現頻率最多的分組記錄(取最小值)


剛剛寫的簡單的動態刪除記錄的存儲過程

create proc pghh
(

@b_sn varchar(50),@tablename varchar(50)
)
as
declare @sql varchar(50)
set @sql= ' delete ' +'from '+ @tablename + ' where '+' b_sn =''' + @b_sn+''''
exec(@sql)

exec pghh '3453', 'book_2'

 


實例學習下
if(@shth='' and @djh='')
begin

--取不同的發票號
 create table #tmp(hh int identity(1,1),fpno varchar(20))
 insert into #tmp(fpno)
 select distinct(fpno) from yyjs
 where ywlxdm=@ywlxdm
  and (len(@dwdm)<=7 and zddm like @dwdm+'%'
  or len(@dwdm)=8 and left(dwdm,8)=@dwdm
  or len(@dwdm)=9 and zddm+fjh=@dwdm
  or len(@dwdm)=10 and left(dwdm,10)=@dwdm
  or len(@dwdm)=14 and dwdm=@dwdm)
  and (comm=0 or comm=3)
  and crq>=@crq1 and crq<=@crq2
  and (@djlx='1'
  or @djlx='2' and zyno='999999'
  or @djlx='3' and zyno='999998'
  or @djlx='4' and zyno not like '9%')
 order by fpno

--計算出按@PageCount分頁後共有多少頁
 declare @PageSize1 decimal(18,2)
 select @PageSize1=cast(@PageSize as varchar(10))+'.00'
 select @PageCount=ceiling(count(*)/@PageSize1) from #tmp
 select @fpzs=count(*) from #tmp --------------------------------總的發票張數
 select @yxzs=count(distinct(fpno)) from yyjs where
 ywlxdm=@ywlxdm
  and (len(@dwdm)<=7 and zddm like @dwdm+'%'
  or len(@dwdm)=8 and left(dwdm,8)=@dwdm
  or len(@dwdm)=9 and zddm+fjh=@dwdm
  or len(@dwdm)=10 and left(dwdm,10)=@dwdm
  or len(@dwdm)=14 and dwdm=@dwdm)
  and (comm=0 or comm=3)
  and crq>=@crq1 and crq<=@crq2
  and c2=''
  and (@djlx='1'
  or @djlx='2' and zyno='999999'
  or @djlx='3' and zyno='999998'
  or @djlx='4' and zyno not like '9%')---------------------有效發票張數
 set @chzs=@fpzs-@yxzs -------------------------------------------衝紅張數
 
 insert into T_sum_SGQDCXTB
 (YHDM,YWLXDM,DWDM,DWMC,FPH,CZDM,CZMC,HTH,SHTH,FZXM,CRQ,ZL,JE,KMBT,PZBT,KKJE,N3,SFJE,KPLX,CHBZ,SGX)
 select @yhdm,@ywlxdm,zddm+fjh as zddm,'',fpno,dwdm,'',hth,'',fzxm,left(crq,4)+'-'+substring(crq,5,2)+'-'+right(crq,2),isnull(sum(zl),0),isnull(sum(je),0),
 isnull(sum(bzje),0),isnull(sum(n2),0),isnull(sum(kkje),0),isnull(sum(n3),0),sum(je)+sum(bzje)+sum(n2)-sum(kkje)-sum(n3),
 case zyno when '999999' then '主機開票' when '999998' then '手工開票' else '補錄發票' end,c2,fjh
 from yyjs
 where ywlxdm=@ywlxdm
 and (len(@dwdm)<=7 and zddm like @dwdm+'%'
 or len(@dwdm)=8 and left(dwdm,8)=@dwdm
 or len(@dwdm)=9 and zddm+fjh=@dwdm
 or len(@dwdm)=10 and left(dwdm,10)=@dwdm
 or len(@dwdm)=14 and dwdm=@dwdm)
 and (comm=0 or comm=3)
 and crq>=@crq1 and crq<=@crq2
 and (@djlx='1'
 or @djlx='2' and zyno='999999'
 or @djlx='3' and zyno='999998'
 or @djlx='4' and zyno not like '9%')
 and(@hth=''
 or hth like '%'+@hth)
 and fpno in (select fpno from #tmp where ceiling(hh/@PageSize1)=@Page)
 group by zddm,fpno,dwdm,hth,fzxm,crq,zyno,c2,fjh

--處理完成後刪除臨時表
 drop table #tmp
end

 
實例:
create proc phoo111
(
   @hs1 varchar(50),@b_id varchar(50),@tablename varchar(50),@rownumber varchar(50),@ys1 varchar(50),@ys2 varchar(50)
)
as
declare @sql varchar(200)
set @sql='select'+' top '  + @hs1+'*'+ ' from'+ '  (select row_number() over (order by '+@b_id+') as rownumber,* from '+@tablename+') A  where '+ @rownumber+ '>'+ @hs1+'*('+@ys1+'-'+@ys2+')'
exec (@sql)
簡單的動態分頁存儲過程

 

增加rollback 回滾和commit 提交事務實例

實例是爲現實效果 可以改下 看下效果
begin tran
    declare @1 varchar(50)
declare @sql varchar(100)
      set @1=1
   while   @1<=100  
  begin
 -- select  @sql= b_id from book_3
  print @1
 set @1 =@1+ 1
 end
   if @1=1
    rollback tran
   else
 print 'noooo'

-------------------------------------------------------------------------------------------------

不多貴在是自己總結的,多少當時也有一點成就感。謝謝各位賞臉了!

 


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章