ms-sql數據庫開發常用匯總 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 @[email protected]+','+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
8.如何修改數據庫的名稱:
sp_renamedb 'old_name', 'new_name'
9:獲取當前數據庫中的所有用戶表
select name from sysobjects where xtype='u' and status>=0
10:獲取某一個表的所有字段
select name from syscolumns where id=object_id('表名')
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 <> 0x01
14:查詢某一個表的字段和數據類型
select column_name,data_type from information_schema.columns
where table_name = '表名'
[n].[標題]:
select * from tablename order by customername
[n].[標題]:
來自http://dev.csdn.net/develop/article/83/83138.shtm
一、 只復制一個表結構,不復制數據
select top 0 * into [t1] from [t2]
二、 獲取數據庫中某個對象的創建腳本
1、 先用下面的腳本創建一個函數
if exists(select 1 from sysobjects where id=object_id('fgetscript') and objectproperty(id,'isinlinefunction')=0)
drop function fgetscript
go
create function fgetscript(
@servername varchar(50) --服務器名
,@userid varchar(50)='sa' --用戶名,如果為nt驗證方式,則為空
,@password varchar(50)='' --密碼
,@databasename varchar(50) --數據庫名稱
,@objectname varchar(250) --對象名
) returns varchar(8000)
as
begin
declare @re varchar(8000) --返回腳本
declare @srvid int,@dbsid int --定義服務器、數據庫集id
declare @dbid int,@tbid int --數據庫、表id
declare @err int,@src varchar(255), @desc varchar(255) --錯誤處理變量
--創建sqldmo對象
exec @err=sp_oacreate 'sqldmo.sqlserver',@srvid output
if @err<>0 goto lberr
--連接服務器
if isnull(@userid,'')='' --如果是 nt驗證方式
begin
exec @err=sp_oasetproperty @srvid,'loginsecure',1
if @err<>0 goto lberr
exec @err=sp_oamethod @srvid,'connect',null,@servername
end
else
exec @err=sp_oamethod @srvid,'connect',null,@servername,@userid,@password
if @err<>0 goto lberr
--獲取數據庫集
exec @err=sp_oagetproperty @srvid,'databases',@dbsid output
if @err<>0 goto lberr
--獲取要取得腳本的數據庫id
exec @err=sp_oamethod @dbsid,'item',@dbid output,@databasename
if @err<>0 goto lberr
--獲取要取得腳本的對象id
exec @err=sp_oamethod @dbid,'getobjectbyname',@tbid output,@objectname
if @err<>0 goto lberr
--取得腳本
exec @err=sp_oamethod @tbid,'script',@re output
if @err<>0 goto lberr
--print @re
return(@re)
lberr:
exec sp_oageterrorinfo null, @src out, @desc out
declare @errb varbinary(4)
set @errb=cast(@err as varbinary(4))
exec master..xp_varbintohexstr @errb,@re out
set @re='錯誤號: '[email protected]
+char(13)+'錯誤源: '[email protected]
+char(13)+'錯誤描述: '[email protected]
return(@re)
end
go
2、 用法如下
用法如下,
print dbo.fgetscript('服務器名','用戶名','密碼','數據庫名','表名或其它對象名')
3、 如果要獲取庫里所有對象的腳本,如如下方式
declare @name varchar(250)
declare #aa cursor for
select name from sysobjects where xtype not in('s','pk','d','x','l')
open #aa
fetch next from #aa into @name
while @@fetch_status=0
begin
print dbo.fgetscript('onlytiancai','sa','sa','database',@name)
fetch next from #aa into @name
end
close #aa
deallocate #aa
4、 聲明,此函數是csdn鄒建鄒老大提供的
三、 分隔字符串
如果有一個用逗號分割開的字符串,比如說"a,b,c,d,1,2,3,4",如何用t-sql獲取這個字符串有幾個元素,獲取第幾個元素的值是多少呢?因為t-sql里沒有split函數,也沒有數組的概念,所以只能自己寫幾個函數了。
1、 獲取元素個數的函數
create function getstrarrlength (@str varchar(8000))
returns int
as
begin
declare @int_return int
declare @start int
declare @next int
declare @location int
select @str =','+ @str +','
select @str=replace(@str,',,',',')
select @start =1
select @next =1
select @location = charindex(',',@str,@start)
while (@location <>0)
begin
select @start = @location +1
select @location = charindex(',',@str,@start)
select @next [email protected] +1
end
select @int_return = @next-2
return @int_return
end
2、 獲取指定索引的值的函數
create function getstrofindex (@str varchar(8000),@index int =0)
returns varchar(8000)
as
begin
declare @str_return varchar(8000)
declare @start int
declare @next int
declare @location int
select @start =1
select @next =1 --如果習慣從0開始則select @next =0
select @location = charindex(',',@str,@start)
while (@location <>0 and @index > @next )
begin
select @start = @location +1
select @location = charindex(',',@str,@start)
select @next [email protected] +1
end
if @location =0 select @location =len(@str)+1 --如果是因為沒有逗號退出,則認為逗號在字符串后
select @str_return = substring(@str,@start,@location [email protected]) [email protected]肯定是逗號之后的位置或者就是初始值1
if (@index <> @next ) select @str_return = '' --如果二者不相等,則是因為逗號太少,或者@index小于@next的初始值1。
return @str_return
end
3、 測試
select [dbo].[getstrarrlength]('1,2,3,4,a,b,c,d')
select [dbo].[getstrofindex]('1,2,3,4,a,b,c,d',5)
四、 一條語句執行跨越若干個數據庫
我要在一條語句里操作不同的服務器上的不同的數據庫里的不同的表,怎么辦呢?
第一種方法:
select * from opendatasource('sqloledb','data source=遠程ip;user id=sa;password=密碼').庫名.dbo.表名
第二種方法:
先使用聯結服務器:
exec sp_addlinkedserver '別名','','msdasql',null,null,'driver={sql server};server=遠程名;uid=用戶;pwd=密碼;'
exec sp_addlinkedsrvlogin @rmtsrvname='別名',@useself='false',@locallogin='sa',@rmtuser='sa',@rmtpassword='密碼'
go
然后你就可以如下:
select * from 別名.庫名.dbo.表名
insert 庫名.dbo.表名 select * from 別名.庫名.dbo.表名
select * into 庫名.dbo.新表名 from 別名.庫名.dbo.表名
go
五、 怎樣獲取一個表中所有的字段信息
蛙蛙推薦:怎樣獲取一個表中所有字段的信息
先創建一個視圖
create view fielddesc
as
select o.name as table_name,c.name as field_name,t.name as type,c.length as
length,c.isnullable as isnullable,convert(varchar(30),p.value) as desp
from syscolumns c
join systypes t on c.xtype = t.xusertype
join sysobjects o on o.id=c.id
left join sysproperties p on p.smallid=c.colid and p.id=o.id
where o.xtype='u'
查詢時:
select * from fielddesc where table_name = '你的表名'
還有個更強的語句,是鄒建寫的,也寫出來吧
select
(case when a.colorder=1 then d.name else '' end) n'表名',
a.colorder n'字段序號',
a.name n'字段名',
(case when columnproperty( a.id,a.name,'isidentity')=1 then '√'else '' end) n'標識',
(case when (select count(*)
from sysobjects
where (name in
(select name
from sysindexes
where (id = a.id) and (indid in
(select indid
from sysindexkeys
where (id = a.id) and (colid in
(select colid
from syscolumns
where (id = a.id) and (name = a.name))))))) and
(xtype = 'pk'))>0 then '√' else '' end) n'主鍵',
b.name n'類型',
a.length n'占用字節數',
columnproperty(a.id,a.name,'precision') as n'長度',
isnull(columnproperty(a.id,a.name,'scale'),0) as n'小數位數',
(case when a.isnullable=1 then '√'else '' end) n'允許空',
isnull(e.text,'') n'默認值',
isnull(g.[value],'') as n'字段說明'
--into ##tx
from syscolumns a left join systypes b
on a.xtype=b.xusertype
inner join sysobjects d
on a.id=d.id and d.xtype='u' and d.name<>'dtproperties'
left join syscomments e
on a.cdefault=e.id
left join sysproperties g
on a.id=g.id and a.colid = g.smallid
order by object_name(a.id),a.colorder
六、 時間格式轉換問題
因為新開發的軟件需要用一些舊軟件生成的一些數據,在時間格式上不統一,只能手工轉換,研究了一下午寫了三條語句,以前沒怎么用過convert函數和case語句,還有"+"操作符在不同上下文環境也會起到不同的作用,把我搞暈了要,不過現在看來是差不多弄好了。
1、把所有"70.07.06"這樣的值變成"1970-07-06"
update lvshi
set shengri = '19' + replace(shengri, '.', '-')
where (zhiyezheng = '139770070153')
2、在"1970-07-06"里提取"70","07","06"
select substring(shengri, 3, 2) as year, substring(shengri, 6, 2) as month,
substring(shengri, 9, 2) as day
from lvshi
where (zhiyezheng = '139770070153')
3、把一個時間類型字段轉換成"1970-07-06"
update lvshi
set shenling = convert(varchar(4), year(shenling))
+ '-' + case when len(month(shenling)) = 1 then '0' + convert(varchar(2),
month(shenling)) else convert(varchar(2), month(shenling))
end + '-' + case when len(day(shenling)) = 1 then '0' + convert(char(2),
day(shenling)) else convert(varchar(2), day(shenling)) end
where (zhiyezheng = '139770070153')
七、 分區視圖
分區視圖是提高查詢性能的一個很好的辦法
--看下面的示例
--示例表
create table tempdb.dbo.t_10(
id int primary key check(id between 1 and 10),name varchar(10))
create table pubs.dbo.t_20(
id int primary key check(id between 11 and 20),name varchar(10))
create table northwind.dbo.t_30(
id int primary key check(id between 21 and 30),name varchar(10))
go
--分區視圖
create view v_t
as
select * from tempdb.dbo.t_10
union all
select * from pubs.dbo.t_20
union all
select * from northwind.dbo.t_30
go
--插入數據
insert v_t select 1 ,'aa'
union all select 2 ,'bb'
union all select 11,'cc'
union all select 12,'dd'
union all select 21,'ee'
union all select 22,'ff'
--更新數據
update v_t set name=name+'_更新' where right(id,1)=1
--刪除測試
delete from v_t where right(id,1)=2
--顯示結果
select * from v_t
go
--刪除測試
drop table northwind.dbo.t_30,pubs.dbo.t_20,tempdb.dbo.t_10
drop view v_t
/**//*--測試結果
id name
----------- ----------
1 aa_更新
11 cc_更新
21 ee_更新
(所影響的行數為 3 行)
==*/
八、 樹型的實現
--參考
--樹形數據查詢示例
--作者: 鄒建
--示例數據
create table [tb]([id] int identity(1,1),[pid] int,name varchar(20))
insert [tb] select 0,'中國'
union all select 0,'美國'
union all select 0,'加拿大'
union all select 1,'北京'
union all select 1,'上海'
union all select 1,'江蘇'
union all select 6,'蘇州'
union all select 7,'常熟'
union all select 6,'南京'
union all select 6,'無錫'
union all select 2,'紐約'
union all select 2,'舊金山'
go
--查詢指定id的所有子
create function f_cid(
@id int
)returns @re table([id] int,[level] int)
as
begin
declare @l int
set @l=0
insert @re select @id,@l
while @@rowcount>0
begin
set @[email protected]+1
insert @re select a.[id],@l
from [tb] a,@re b
where a.[pid]=b.[id] and b.[level][email protected]
end
/**//**//**//*--如果只顯示最明細的子(下面沒有子),則加上這個刪除
delete a from @re a
where exists(
select 1 from [tb] where [pid]=a.[id])
--*/
return
end
go
--調用(查詢所有的子)
select a.*,層次=b.[level] from [tb] a,f_cid(2)b where a.[id]=b.[id]
go
--刪除測試
drop table [tb]
drop function f_cid
go
九、 排序問題
create table [t] (
[id] [int] identity (1, 1) not null ,
[guid] [uniqueidentifier] null
) on [primary]
go
下面這句執行5次
insert t values (newid())
查看執行結果
select * from t
1、 第一種
select * from t
order by case id when 4 then 1
when 5 then 2
when 1 then 3
when 2 then 4
when 3 then 5 end
2、 第二種
select * from t order by (id+2)%6
3、 第三種
select * from t order by charindex(cast(id as varchar),'45123')
4、 第四種
select * from t
where id between 0 and 5
order by charindex(cast(id as varchar),'45123')
5、 第五種
select * from t order by case when id >3 then id-5 else id end
6、 第六種
select * from t order by id / 4 desc,id asc
十、 一條語句刪除一批記錄
首先id列是int標識類類型,然后刪除id值為5,6,8,9,10,11的列,這里的cast函數不能用convert函數代替,而且轉換的類型必須是varchar,而不能是char,否則就會執行出你不希望的結果,這里的"5,6,8,9,10,11"可以是你在頁面上獲取的一個chkboxlist構建成的值,然后用下面的一句就全部刪
除了,比循環用多條語句高效吧應該。
delete from [fujian] where charindex(','+cast([id] as varchar)+',',','+'5,6,8,9,10,11,'+',')>0
還有一種就是
delete from table1 where id in(1,2,3,4 )
十一、獲取子表內的一列數據的組合字符串
下面這個函數獲取05年已經注冊了的某個所的律師,唯一一個參數就是事務所的名稱,然后返回zhuce字段里包含05字樣的所有律師。
create function fn_get05lvshinamebysuo (@p_suo nvarchar(50))
returns nvarchar(2000)
as
begin
declare @lvshinames varchar(2000), @name varchar(50)
select @lvshinames=''
declare lvshi_cursor cursor for
數據庫里有1,2,3,4,5 共5條記錄,要用一條sql語句讓其排序,使它排列成4,5,1,2,3,怎么寫?
--數據操作
select --從數據庫表中檢索數據行和列
insert --向數據庫表添加新數據行
delete --從數據庫表中刪除數據行
update --更新數據庫表中的數據
--數據定義
create table --創建一個數據庫表
drop table --從數據庫中刪除表
alter table --修改數據庫表結構
create view --創建一個視圖
drop view --從數據庫中刪除視圖
create index --為數據庫表創建一個索引
drop index --從數據庫中刪除索引
create procedure --創建一個存儲過程
drop procedure --從數據庫中刪除存儲過程
create trigger --創建一個觸發器
drop trigger --從數據庫中刪除觸發器
create schema --向數據庫添加一個新模式
drop schema --從數據庫中刪除一個模式
create domain --創建一個數據值域
alter domain --改變域定義
drop domain --從數據庫中刪除一個域
--數據控制
grant --授予用戶訪問權限
deny --拒絕用戶訪問
revoke --解除用戶訪問權限
--事務控制
commit --結束當前事務
rollback --中止當前事務
set transaction --定義當前事務數據訪問特征
--程序化sql
declare --為查詢設定游標
explan --為查詢描述數據訪問計劃
open --檢索查詢結果打開一個游標
fetch --檢索一行查詢結果
close --關閉游標
prepare --為動態執行準備sql 語句
execute --動態地執行sql 語句
describe --描述準備好的查詢
---局部變量
declare @id char(10)
--set @id = '10010001'
select @id = '10010001'
---全局變量
---必須以@@開頭
--if else
declare @x int @y int @z int
select @x = 1 @y = 2 @z=3
if @x > @y
print 'x > y' --打印字符串'x > y'
else if @y > @z
print 'y > z'
else print 'z > y'
--case
use pangu
update employee
set e_wage =
case
when job_level = ’1’ then e_wage*1.08
when job_level = ’2’ then e_wage*1.07
when job_level = ’3’ then e_wage*1.06
else e_wage*1.05
end
--while continue break
declare @x int @y int @c int
select @x = 1 @y=1
while @x < 3
begin
print @x --打印變量x 的值
while @y < 3
begin
select @c = 100*@x + @y
print @c --打印變量c 的值
select @y = @y + 1
end
select @x = @x + 1
select @y = 1
end
--waitfor
--例 等待1 小時2 分零3 秒后才執行select 語句
waitfor delay ’01:02:03’
select * from employee
--例 等到晚上11 點零8 分后才執行select 語句
waitfor time ’23:08:00’
select
select *(列名) from table_name(表名) where column_name operator value ex宿主)
select * from stock_information where stockid = str(nid)
stockname = 'str_name'
stockname like '% find this %'
stockname like '[a-za-z]%' --------- ([]指定值的范圍)
stockname like '[^f-m]%' --------- (^排除指定范圍)
--------- 只能在使用like關鍵字的where子句中使用通配符)
or stockpath = 'stock_path'
or stocknumber < 1000
and stockindex = 24
not stocksex = 'man'
stocknumber between 20 and 100
stocknumber in(10,20,30)
order by stockid desc(asc) --------- 排序,desc-降序,asc-升序
order by 1,2 --------- by列號
stockname = (select stockname from stock_information where stockid = 4)
--------- 子查詢
--------- 除非能確保內層select只返回一個行的值
--------- 否則應在外層where子句中用一個in限定符
select distinct column_name form table_name
--------- distinct指定檢索獨有的列值,不重復
select stocknumber ,"stocknumber + 10" = stocknumber + 10 from table_name
select stockname , "stocknumber" = count(*) from table_name group by stockname
--------- group by 將表按行分組,指定列中有相同的值
having count(*) = 2 --------- having選定指定的組
select *
from table1, table2
where table1.id *= table2.id -------- 左外部連接,table1中有的而table2中沒有得以null表示
table1.id =* table2.id -------- 右外部連接
select stockname from table1
union [all] -------- union合并查詢結果集,all-保留重復行
select stockname from table2
insert
insert into table_name (stock_name,stock_number) value ("xxx","xxxx"
value (select stockname , stocknumber from stock_table2)
-------value為select語句
update
update table_name set stockname = "xxx" [where stockid = 3]
stockname = default
stockname = null
stocknumber = stockname + 4
delete
delete from table_name where stockid = 3
truncate table_name --------- 刪除表中所有行,仍保持表的完整性
drop table table_name --------- 完全刪除表
alter table -------- 修改數據庫表結構
alter table database.owner.table_name add column_name char(2) null ..
sp_help table_name -------- 顯示表已有特征
create table table_name (name char(20), age smallint, lname varchar(30))
insert into table_name select -------- 實現刪除列的方法(創建新表)
alter table table_name drop constraint stockname_default
--------- 刪除stockname的default約束
常用函數(function)
轉換函數
convert(數據類型,值,格式)
統計函數
avg --求平均值
count --統計數目
max --求最大值
min --求最小值
sum --求和
avg
use pangu
select avg(e_wage) as dept_avgwage
from employee
group by dept_id
max
--求工資最高的員工姓名
use pangu
select e_name
from employee
where e_wage =
(select max(e_wage)
from employee)
stdev()
--stdev()函數返回表達式中所有數據的標準差
--stdevp()
--stdevp()函數返回總體標準差
var()
--var()函數返回表達式中所有值的統計變異數
varp()
--varp()函數返回總體變異數
算術函數
三角函數
sin(float_expression) --返回以弧度表示的角的正弦
cos(float_expression) --返回以弧度表示的角的余弦
tan(float_expression) --返回以弧度表示的角的正切
cot(float_expression) --返回以弧度表示的角的余切
反三角函數
asin(float_expression) --返回正弦是float 值的以弧度表示的角
acos(float_expression) --返回余弦是float 值的以弧度表示的角
atan(float_expression) --返回正切是float 值的以弧度表示的角
atan2(float_expression1,float_expression2)
------返回正切是float_expression1 /float_expres-sion2的以弧度表示的角
degrees(numeric_expression)
------把弧度轉換為角度返回與表達式相同的數據類型可為
------integer/money/real/float 類型
radians(numeric_expression)
------把角度轉換為弧度返回與表達式相同的數據類型可為
------integer/money/real/float 類型
exp(float_expression) --返回表達式的指數值
log(float_expression) --返回表達式的自然對數值
log10(float_expression)--返回表達式的以10 為底的對數值
sqrt(float_expression) --返回表達式的平方根
取近似值函數
ceiling(numeric_expression)
-------返回>=表達式的最小整數返回的數據類型與表達式相同可為
-------integer/money/real/float 類型
floor(numeric_expression)
-------返回<=表達式的最小整數返回的數據類型與表達式相同可為
-------integer/money/real/float 類型
round(numeric_expression)
-------返回以integer_expression 為精度的四舍五入值返回的數據
-------類型與表達式相同可為integer/money/real/float 類型
abs(numeric_expression)
-------返回表達式的絕對值返回的數據類型與表達式相同可為
-------integer/money/real/float 類型
sign(numeric_expression)
-------測試參數的正負號返回0 零值1 正數或-1 負數返回的數據類型
-------與表達式相同可為integer/money/real/float 類型
pi() -------返回值為π 即3.1415926535897936
rand([integer_expression])
-------用任選的[integer_expression]做種子值得出0-1 間的隨機浮點數
字符串函數
ascii() ------函數返回字符表達式最左端字符的ascii 碼值
char() ------函數用于將ascii 碼轉換為字符
------如果沒有輸入0 ~ 255 之間的ascii 碼值char 函數會返回一個null 值
lower() ------函數把字符串全部轉換為小寫
upper() ------函數把字符串全部轉換為大寫
str() ------函數把數值型數據轉換為字符型數據
ltrim() ------函數把字符串頭部的空格去掉
rtrim() ------函數把字符串尾部的空格去掉
left(),right(),substring() --函數返回部分字符串
charindex(),patindex() --函數返回字符串中某個指定的子串出現的開始位置
soundex() ------函數返回一個四位字符碼
------soundex函數可用來查找聲音相似的字符串但soundex函數對數字和漢字均只返回0 值
difference() ------函數返回由soundex 函數返回的兩個字符表達式的值的差異
------0 兩個soundex 函數返回值的第一個字符不同
------1 兩個soundex 函數返回值的第一個字符相同
------2 兩個soundex 函數返回值的第一二個字符相同
------3 兩個soundex 函數返回值的第一二三個字符相同
------4 兩個soundex 函數返回值完全相同同
quotename() ------函數返回被特定字符括起來的字符串
/**//**//**//*select quotename('abc', '{') quotename('abc')
運行結果如下
{
{abc} [abc]*/
replicate() ------函數返回一個重復character_expression 指定次數的字符串
/**//**//**//*select replicate('abc', 3) replicate( 'abc', -2)
運行結果如下
abcabcabc null*/
reverse() ------函數將指定的字符串的字符排列順序顛倒
replace() ------函數返回被替換了指定子串的字符串
/**//**//**//*select replace('abc123g', '123', 'def')
運行結果如下
abcdefg*/
space() ------函數返回一個有指定長度的空白字符串
stuff() ------函數用另一子串替換字符串指定位置長度的子串
數據類型轉換函數
cast() 函數語法如下
cast() ( as [ length ])
convert() 函數語法如下
convert() ([ length ], [, style])
select cast(100+99 as char) convert(varchar(12), getdate())
運行結果如下
199 jan 15 2000
日期函數
day() ------函數返回date_expression 中的日期值
month() ------函數返回date_expression 中的月份值
year() ------函數返回date_expression 中的年份值
dateadd( , ,)
-----函數返回指定日期date 加上指定的額外日期間隔number 產生的新日期
datediff( , ,)
-----函數返回兩個指定日期在datepart 方面的不同之處
datename( , ------函數以字符串的形式返回日期的指定部分
datepart( , ------函數以整數值的形式返回日期的指定部分
getdate() ------函數以datetime 的缺省格式返回系統當前的日期和時間
系統函數
app_name() ------函數返回當前執行的應用程序的名稱
coalesce() -----函數返回眾多表達式中第一個非null 表達式的值
col_length(<'table_name'>, <'column_name'> ----函數返回表中指定字段的長度值
col_name(, ----函數返回表中指定字段的名稱即列名
datalength() -----函數返回數據表達式的數據的實際長度
db_id(['database_name']) ------函數返回數據庫的編號
db_name(database_id) ------函數返回數據庫的名稱
host_id() -----函數返回服務器端計算機的名稱
host_name() -----函數返回服務器端計算機的名稱
identity([, seed increment]) [as column_name])
--identity() 函數只在select into 語句中使用用于插入一個identity column列到新表中
/**//**//**//*select identity(int, 1, 1) as column_name
into newtable
from oldtable*/
isdate() ----函數判斷所給定的表達式是否為合理日期
isnull(, --函數將表達式中的null 值用指定值替換
isnumeric() ----函數判斷所給定的表達式是否為合理的數值
newid() ----函數返回一個uniqueidentifier 類型的數值
nullif(,
----nullif 函數在expression1 與expression2 相等時返回null 值若不相等時則返回xpression1 的值 *******************transact_sql********************
--語 句 功 能
--數據操作
select --從數據庫表中檢索數據行和列
insert --向數據庫表添加新數據行
delete --從數據庫表中刪除數據行
update --更新數據庫表中的數據
--數據定義
create table --創建一個數據庫表
drop table --從數據庫中刪除表
alter table --修改數據庫表結構
create view --創建一個視圖
drop view --從數據庫中刪除視圖
create index --為數據庫表創建一個索引
drop index --從數據庫中刪除索引
create procedure --創建一個存儲過程
drop procedure --從數據庫中刪除存儲過程
create trigger --創建一個觸發器
drop trigger --從數據庫中刪除觸發器
create schema --向數據庫添加一個新模式
drop schema --從數據庫中刪除一個模式
create domain --創建一個數據值域
alter domain --改變域定義
drop domain --從數據庫中刪除一個域
--數據控制
grant --授予用戶訪問權限
deny --拒絕用戶訪問
revoke --解除用戶訪問權限
--事務控制
commit --結束當前事務
rollback --中止當前事務
set transaction --定義當前事務數據訪問特征
--程序化sql
declare --為查詢設定游標
explan --為查詢描述數據訪問計劃
open --檢索查詢結果打開一個游標
fetch --檢索一行查詢結果
close --關閉游標
prepare --為動態執行準備sql 語句
execute --動態地執行sql 語句
describe --描述準備好的查詢
---局部變量
declare @id char(10)
--set @id = '10010001'
select @id = '10010001'
---全局變量
---必須以@@開頭
--if else
declare @x int @y int @z int
select @x = 1 @y = 2 @z=3
if @x > @y
print 'x > y' --打印字符串'x > y'
else if @y > @z
print 'y > z'
else print 'z > y'
--case
use pangu
update employee
set e_wage =
case
when job_level = ’1’ then e_wage*1.08
when job_level = ’2’ then e_wage*1.07
when job_level = ’3’ then e_wage*1.06
else e_wage*1.05
end
--while continue break
declare @x int @y int @c int
select @x = 1 @y=1
while @x < 3
begin
print @x --打印變量x 的值
while @y < 3
begin
select @c = 100*@x + @y
print @c --打印變量c 的值
select @y = @y + 1
end
select @x = @x + 1
select @y = 1
end
--waitfor
--例 等待1 小時2 分零3 秒后才執行select 語句
waitfor delay ’01:02:03’
select * from employee
--例 等到晚上11 點零8 分后才執行select 語句
waitfor time ’23:08:00’
select * from employee
***select***
select *(列名) from table_name(表名) where column_name operator value
ex:(宿主)
select * from stock_information where stockid = str(nid)
stockname = 'str_name'
stockname like '% find this %'
stockname like '[a-za-z]%' --------- ([]指定值的范圍)
stockname like '[^f-m]%' --------- (^排除指定范圍)
--------- 只能在使用like關鍵字的where子句中使用通配符)
or stockpath = 'stock_path'
or stocknumber < 1000
and stockindex = 24
not stocksex = 'man'
stocknumber between 20 and 100
stocknumber in(10,20,30)
order by stockid desc(asc) --------- 排序,desc-降序,asc-升序
order by 1,2 --------- by列號
stockname = (select stockname from stock_information where stockid = 4)
--------- 子查詢
--------- 除非能確保內層select只返回一個行的值,
--------- 否則應在外層where子句中用一個in限定符
select distinct column_name form table_name --------- distinct指定檢索獨有的列值,不重復
select stocknumber ,"stocknumber + 10" = stocknumber + 10 from table_name
select stockname , "stocknumber" = count(*) from table_name group by stockname
--------- group by 將表按行分組,指定列中有相同的值
having count(*) = 2 --------- having選定指定的組
select *
from table1, table2
where table1.id *= table2.id -------- 左外部連接,table1中有的而table2中沒有得以null表示
table1.id =* table2.id -------- 右外部連接
select stockname from table1
union [all] ----- union合并查詢結果集,all-保留重復行
select stockname from table2
***insert***
insert into table_name (stock_name,stock_number) value ("xxx","xxxx")
value (select stockname , stocknumber from stock_table2)---value為select語句
***update***
update table_name set stockname = "xxx" [where stockid = 3]
stockname = default
stockname = null
stocknumber = stockname + 4
***delete***
delete from table_name where stockid = 3
truncate table_name ----------- 刪除表中所有行,仍保持表的完整性
drop table table_name --------------- 完全刪除表
***alter table*** --- 修改數據庫表結構
alter table database.owner.table_name add column_name char(2) null ..
sp_help table_name ---- 顯示表已有特征
create table table_name (name char(20), age smallint, lname varchar(30))
insert into table_name select ----- 實現刪除列的方法(創建新表)
alter table table_name drop constraint stockname_default ---- 刪除stockname的default約束
***function(/**//*常用函數*/)***
----統計函數----
avg --求平均值
count --統計數目
max --求最大值
min --求最小值
sum --求和
--avg
use pangu
select avg(e_wage) as dept_avgwage
from employee
group by dept_id
--max
--求工資最高的員工姓名
use pangu
select e_name
from employee
where e_wage =
(select max(e_wage)
from employee)
--stdev()
--stdev()函數返回表達式中所有數據的標準差
--stdevp()
--stdevp()函數返回總體標準差
--var()
--var()函數返回表達式中所有值的統計變異數
--varp()
--varp()函數返回總體變異數
----算術函數----
/**//***三角函數***/
sin(float_expression) --返回以弧度表示的角的正弦
cos(float_expression) --返回以弧度表示的角的余弦
tan(float_expression) --返回以弧度表示的角的正切
cot(float_expression) --返回以弧度表示的角的余切
/**//***反三角函數***/
asin(float_expression) --返回正弦是float 值的以弧度表示的角
acos(float_expression) --返回余弦是float 值的以弧度表示的角
atan(float_expression) --返回正切是float 值的以弧度表示的角
atan2(float_expression1,float_expression2)
--返回正切是float_expression1 /float_expres-sion2的以弧度表示的角
degrees(numeric_expression)
--把弧度轉換為角度返回與表達式相同的數據類型可為
--integer/money/real/float 類型
radians(numeric_expression) --把角度轉換為弧度返回與表達式相同的數據類型可為
--integer/money/real/float 類型
exp(float_expression) --返回表達式的指數值
log(float_expression) --返回表達式的自然對數值
log10(float_expression)--返回表達式的以10 為底的對數值
sqrt(float_expression) --返回表達式的平方根
/**//***取近似值函數***/
ceiling(numeric_expression) --返回>=表達式的最小整數返回的數據類型與表達式相同可為
--integer/money/real/float 類型
floor(numeric_expression) --返回<=表達式的最小整數返回的數據類型與表達式相同可為
--integer/money/real/float 類型
round(numeric_expression) --返回以integer_expression 為精度的四舍五入值返回的數據
--類型與表達式相同可為integer/money/real/float 類型
abs(numeric_expression) --返回表達式的絕對值返回的數據類型與表達式相同可為
--integer/money/real/float 類型
sign(numeric_expression) --測試參數的正負號返回0 零值1 正數或-1 負數返回的數據類型
--與表達式相同可為integer/money/real/float 類型
pi() --返回值為π 即3.1415926535897936
rand([integer_expression]) --用任選的[integer_expression]做種子值得出0-1 間的隨機浮點數
----字符串函數----
ascii() --函數返回字符表達式最左端字符的ascii 碼值
char() --函數用于將ascii 碼轉換為字符
--如果沒有輸入0 ~ 255 之間的ascii 碼值char 函數會返回一個null 值
lower() --函數把字符串全部轉換為小寫
upper() --函數把字符串全部轉換為大寫
str() --函數把數值型數據轉換為字符型數據
ltrim() --函數把字符串頭部的空格去掉
rtrim() --函數把字符串尾部的空格去掉
left(),right(),substring() --函數返回部分字符串
charindex(),patindex() --函數返回字符串中某個指定的子串出現的開始位置
soundex() --函數返回一個四位字符碼
--soundex函數可用來查找聲音相似的字符串但soundex函數對數字和漢字均只返回0 值
difference() --函數返回由soundex 函數返回的兩個字符表達式的值的差異
--0 兩個soundex 函數返回值的第一個字符不同
--1 兩個soundex 函數返回值的第一個字符相同
--2 兩個soundex 函數返回值的第一二個字符相同
--3 兩個soundex 函數返回值的第一二三個字符相同
--4 兩個soundex 函數返回值完全相同
quotename() --函數返回被特定字符括起來的字符串
/**//*select quotename('abc', '{') quotename('abc')
運行結果如下
----------------------------------{
{abc} [abc]*/
replicate() --函數返回一個重復character_expression 指定次數的字符串
/**//*select replicate('abc', 3) replicate( 'abc', -2)
運行結果如下
----------- -----------
abcabcabc null*/
reverse() --函數將指定的字符串的字符排列順序顛倒
replace() --函數返回被替換了指定子串的字符串
/**//*select replace('abc123g', '123', 'def')
運行結果如下
----------- -----------
abcdefg*/
space() --函數返回一個有指定長度的空白字符串
stuff() --函數用另一子串替換字符串指定位置長度的子串
----數據類型轉換函數----
cast() 函數語法如下
cast() (<expression> as <data_ type>[ length ])
convert() 函數語法如下
convert() (<data_ type>[ length ], <expression> [, style])
select cast(100+99 as char) convert(varchar(12), getdate())
運行結果如下
------------------------------ ------------
199 jan 15 2000
----日期函數----
day() --函數返回date_expression 中的日期值
month() --函數返回date_expression 中的月份值
year() --函數返回date_expression 中的年份值
dateadd(<datepart> ,<number> ,<date>)
--函數返回指定日期date 加上指定的額外日期間隔number 產生的新日期
datediff(<datepart> ,<number> ,<date>)
--函數返回兩個指定日期在datepart 方面的不同之處
datename(<datepart> , <date>) --函數以字符串的形式返回日期的指定部分
datepart(<datepart> , <date>) --函數以整數值的形式返回日期的指定部分
getdate() --函數以datetime 的缺省格式返回系統當前的日期和時間
----系統函數----
app_name() --函數返回當前執行的應用程序的名稱
coalesce() --函數返回眾多表達式中第一個非null 表達式的值
col_length(<'table_name'>, <'column_name'>) --函數返回表中指定字段的長度值
col_name(<table_id>, <column_id>) --函數返回表中指定字段的名稱即列名
datalength() --函數返回數據表達式的數據的實際長度
db_id(['database_name']) --函數返回數據庫的編號
db_name(database_id) --函數返回數據庫的名稱
host_id() --函數返回服務器端計算機的名稱
host_name() --函數返回服務器端計算機的名稱
identity(<data_type>[, seed increment]) [as column_name])
--identity() 函數只在select into 語句中使用用于插入一個identity column列到新表中
/**//*select identity(int, 1, 1) as column_name
into newtable
from oldtable*/
isdate() --函數判斷所給定的表達式是否為合理日期
isnull(<check_expression>, <replacement_value>) --函數將表達式中的null 值用指定值替換
isnumeric() --函數判斷所給定的表達式是否為合理的數值
newid() --函數返回一個uniqueidentifier 類型的數值
nullif(<expression1>, <expression2>)
--nullif 函數在expression1 與expression2 相等時返回null 值若不相等時則返回expression1 的值
新聞熱點
疑難解答