交*表語(yǔ)句的實(shí)現(xiàn):
--用于:交*表的列數(shù)是確定的
select name,sum(case subject when ‘?dāng)?shù)學(xué)‘ then source else 0 end) as ‘?dāng)?shù)學(xué)‘,
sum(case subject when ‘英語(yǔ)‘ then source else 0 end) as ‘英語(yǔ)‘,
sum(case subject when ‘語(yǔ)文‘ then source else 0 end) as ‘語(yǔ)文‘
from test
group by name
--用于:交*表的列數(shù)是不確定的
declare @sql varchar(8000)
set @sql = ‘select name,‘
select @sql = @sql + ‘sum(case subject when ‘‘‘+subject+‘‘‘
then source else 0 end) as ‘‘‘+subject+‘‘‘,‘
from (select distinct subject from test) as a
select @sql = left(@sql,len(@sql)-1) + ‘ from test group by name‘
exec(@sql)
go
================================================================================
SQL Server 存儲(chǔ)過(guò)程的分頁(yè)方案比拼
出處
SQL Server 存儲(chǔ)過(guò)程的分頁(yè),這個(gè)問(wèn)題已經(jīng)討論過(guò)幾年了,很多朋友在問(wèn)我,所以在此發(fā)表一下我的觀點(diǎn)
建立表:
CREATE TABLE [TestTable] (
[ID] [int] IDENTITY (1, 1) NOT NULL ,
[FirstName] [nvarchar] (100) COLLATE Chinese_PRC_CI_AS NULL ,
[LastName] [nvarchar] (100) COLLATE Chinese_PRC_CI_AS NULL ,
[Country] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[Note] [nvarchar] (2000) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]
GO
插入數(shù)據(jù):(2萬(wàn)條,用更多的數(shù)據(jù)測(cè)試會(huì)明顯一些)
SET IDENTITY_INSERT TestTable ON
declare @i int
set @i=1
while @i<=20000
begin
insert into TestTable([id], FirstName, LastName, Country,Note) values(@i, ‘FirstName_XXX‘,‘LastName_XXX‘,‘Country_XXX‘,‘Note_XXX‘)
set @i=@i+1
end
SET IDENTITY_INSERT TestTable OFF
-------------------------------------
分頁(yè)方案一:(利用Not In和SELECT TOP分頁(yè))
語(yǔ)句形式:
SELECT TOP 10 *
FROM TestTable
WHERE (ID NOT IN
(SELECT TOP 20 id
FROM TestTable
ORDER BY id))
ORDER BY ID
SELECT TOP 頁(yè)大小 *
FROM TestTable
WHERE (ID NOT IN
(SELECT TOP 頁(yè)大小*頁(yè)數(shù) id
FROM 表
ORDER BY id))
ORDER BY ID
-------------------------------------
分頁(yè)方案二:(利用ID大于多少和SELECT TOP分頁(yè))
語(yǔ)句形式:
SELECT TOP 10 *
FROM TestTable
WHERE (ID >
(SELECT MAX(id)
FROM (SELECT TOP 20 id
FROM TestTable
ORDER BY id) AS T))
ORDER BY ID
SELECT TOP 頁(yè)大小 *
FROM TestTable
WHERE (ID >
(SELECT MAX(id)
FROM (SELECT TOP 頁(yè)大小*頁(yè)數(shù) id
FROM 表
ORDER BY id) AS T))
ORDER BY ID
-------------------------------------
分頁(yè)方案三:(利用SQL的游標(biāo)存儲(chǔ)過(guò)程分頁(yè))
create procedure XiaoZhengGe
@sqlstr nvarchar(4000), --查詢字符串
@currentpage int, --第N頁(yè)
@pagesize int --每頁(yè)行數(shù)
as
set nocount on
declare @P1 int, --P1是游標(biāo)的id
@rowcount int
exec sp_cursoropen @P1 output,@sqlstr,@scrollopt=1,@ccopt=1,@rowcount=@rowcount output
select ceiling(1.0*@rowcount/@pagesize) as 總頁(yè)數(shù)--,@rowcount as 總行數(shù),@currentpage as 當(dāng)前頁(yè)
set @currentpage=(@currentpage-1)*@pagesize+1
exec sp_cursorfetch @P1,16,@currentpage,@pagesize
exec sp_cursorclose @P1
set nocount off
其它的方案:如果沒(méi)有主鍵,可以用臨時(shí)表,也可以用方案三做,但是效率會(huì)低。
建議優(yōu)化的時(shí)候,加上主鍵和索引,查詢效率會(huì)提高。
通過(guò)SQL 查詢分析器,顯示比較:我的結(jié)論是:
分頁(yè)方案二:(利用ID大于多少和SELECT TOP分頁(yè))效率最高,需要拼接SQL語(yǔ)句
分頁(yè)方案一:(利用Not In和SELECT TOP分頁(yè)) 效率次之,需要拼接SQL語(yǔ)句
分頁(yè)方案三:(利用SQL的游標(biāo)存儲(chǔ)過(guò)程分頁(yè)) 效率最差,但是最為通用
在實(shí)際情況中,要具體分析。
====================================================================================
得到隨機(jī)排序結(jié)果
出處
SELECT *
FROM Northwind..Orders
ORDER BY NEWID()
SELECT TOP 10 *
FROM Northwind..Orders
ORDER BY NEWID()
====================================================================================
select
to_char(日期,‘yyyymmdd‘) DATE_ID,to_char(日期,‘yyyy‘)||‘年‘||to_char(日期,‘mm‘)||‘月‘||to_char(日期,‘dd‘)||‘日‘ DATE_NAME,
to_char(日期,‘yyyymm‘) MONTH_ID,to_char(日期,‘yyyy‘)||‘年‘||to_char(日期,‘mm‘)||‘月‘ MONTH_NAME,
‘Q‘||to_char(日期,‘q.yyyy‘) QUARTERID,to_char(日期,‘yyyy‘)||‘年第‘||to_char(日期,‘q‘)||‘季度‘ QUARTERID_NAME,
to_char(日期,‘yyyy‘) YEAR_ID,to_char(日期,‘yyyy‘)||‘年‘ YEAR_NAME
from(
select to_date(‘2000-01-01‘,‘yyyy-mm-dd‘)+(rownum-1) 日期 from user_objects where rownum<367 and to_date(‘2000-01-01‘,‘yyyy-mm-dd‘)+(rownum-1)<to_date(‘2001-01-01‘,‘yyyy-mm-dd‘)
);
--得到季度和月份對(duì)應(yīng)關(guān)系
select distinct to_char(日期,‘q‘) 季度,to_char(to_date(‘2001-01-01‘,‘yyyy-mm-dd‘)+(rownum-1),‘yyyymm‘) 日期 from(
select to_date(‘2001-01‘,‘yyyy-mm‘)+(rownum-1) 日期 from user_objects where rownum<367 and to_date(‘2001-01-01‘,‘yyyy-mm-dd‘)+(rownum-1)<to_date(‘2002-01-01‘,‘yyyy-mm-dd‘)
);
--得到一年中的天數(shù)
select to_char(to_date(‘2000-01-01‘,‘yyyy-mm-dd‘)+(rownum-1),‘yyyy-mm-dd‘) 日期 from user_objects where rownum<367 and to_date(‘2000-01-01‘,‘yyyy-mm-dd‘)+(rownum-1)<to_date(‘2001-01-01‘,‘yyyy-mm-dd‘);
====================================================================================
獲取一個(gè)數(shù)據(jù)庫(kù)的所有存儲(chǔ)過(guò)程,可以用
select * from sysobjects where type=‘p‘
====================================================================================
生成交*表的簡(jiǎn)單通用存儲(chǔ)過(guò)程
出處
if exists (select * from dbo.sysobjects where id = object_id(N‘[dbo].[p_qry]‘) and OBJECTPROPERTY(id, N‘IsProcedure‘) = 1)
drop procedure [dbo].[p_qry]
GO
/*--生成交*表的簡(jiǎn)單通用存儲(chǔ)過(guò)程
根據(jù)指定的表名,縱橫字段,統(tǒng)計(jì)字段,自動(dòng)生成交*表
并可根據(jù)需要生成縱橫兩個(gè)方向的合計(jì)
注意,橫向字段數(shù)目如果大于縱向字段數(shù)目,將自動(dòng)交換縱橫字段
如果不要此功能,則去掉交換處理部分
--鄒建 204.06--*/
/*--調(diào)用示例
exec p_qry ‘syscolumns‘,‘id‘,‘colid‘,‘colid‘,1,1
--*/
create proc p_qry
@TableName sysname, --表名
@縱軸 sysname, --交*表最左面的列
@橫軸 sysname, --交*表最上面的列
@表體內(nèi)容 sysname, --交*表的數(shù)數(shù)據(jù)字段
@是否加橫向合計(jì) bit,--為1時(shí)在交*表橫向最右邊加橫向合計(jì)
@是否家縱向合計(jì) bit --為1時(shí)在交*表縱向最下邊加縱向合計(jì)
as
declare @s nvarchar(4000),@sql varchar(8000)
--判斷橫向字段是否大于縱向字段數(shù)目,如果是,則交換縱橫字段
set @s=‘declare @a sysname
if(select case when count(distinct [‘+@縱軸+‘])<count(distinct [‘+@橫軸+‘]) then 1 else 0 end
from [‘+@TableName+‘])=1
select @a=@縱軸,@縱軸=@橫軸,@橫軸=@a‘
exec sp_executesql @s
,N‘@縱軸 sysname out,@橫軸 sysname out‘
,@縱軸 out,@橫軸 out
--生成交*表處理語(yǔ)句
set @s=‘
set @s=‘‘‘‘
select @s=@s+‘‘,[‘‘+cast([‘+@橫軸+‘] as varchar)+‘‘]=sum(case [‘+@橫軸
+‘] when ‘‘‘‘‘‘+cast([‘+@橫軸+‘] as varchar)+‘‘‘‘‘‘ then [‘+@表體內(nèi)容+‘] else 0 end)‘‘
from [‘+@TableName+‘]
group by [‘+@橫軸+‘]‘
exec sp_executesql @s
,N‘@s varchar(8000) out‘
,@sql out
--是否生成合計(jì)字段的處理
declare @sum1 varchar(200),@sum2 varchar(200),@sum3 varchar(200)
select @sum1=case @是否加橫向合計(jì)
when 1 then ‘,[合計(jì)]=sum([‘+@表體內(nèi)容+‘])‘
else ‘‘ end
,@sum2=case @是否家縱向合計(jì)
when 1 then ‘[‘+@縱軸+‘]=case grouping([‘
+@縱軸+‘]) when 1 then ‘‘合計(jì)‘‘ else cast([‘
+@縱軸+‘] as varchar) end‘
else ‘[‘+@縱軸+‘]‘ end
,@sum3=case @是否家縱向合計(jì)
when 1 then ‘ with rollup‘
else ‘‘ end
--生成交*表
exec(‘select ‘+@sum2+@sql+@sum1+‘
from [‘+@TableName+‘]
group by [‘+@縱軸+‘]‘+@sum3)
go
==========================================================================================================
利用排序規(guī)則特點(diǎn)計(jì)算漢字筆劃和取得拼音首字母
出處
SQL SERVER的排序規(guī)則平時(shí)使用不是很多,也許不少初學(xué)者還比較陌生,但有
一個(gè)錯(cuò)誤大家應(yīng)是經(jīng)常碰到: SQL SERVER數(shù)據(jù)庫(kù),在跨庫(kù)多表連接查詢時(shí),若兩數(shù)據(jù)
庫(kù)默認(rèn)字符集不同,系統(tǒng)就會(huì)返回這樣的錯(cuò)誤:
“無(wú)法解決 equal to 操作的排序規(guī)則沖突。”
一.錯(cuò)誤分析:
這個(gè)錯(cuò)誤是因?yàn)榕判蛞?guī)則不一致造成的,我們做個(gè)測(cè)試,比如:
create table #t1(
name varchar(20) collate Albanian_CI_AI_WS,
value int)
create table #t2(
name varchar(20) collate Chinese_PRC_CI_AI_WS,
value int )
表建好后,執(zhí)行連接查詢:
select * from #t1 A inner join #t2 B on A.name=B.name
這樣,錯(cuò)誤就出現(xiàn)了:
服務(wù)器: 消息 446,級(jí)別 16,狀態(tài) 9,行 1
無(wú)法解決 equal to 操作的排序規(guī)則沖突。
要排除這個(gè)錯(cuò)誤,最簡(jiǎn)單方法是,表連接時(shí)指定它的排序規(guī)則,這樣錯(cuò)誤就
不再出現(xiàn)了。語(yǔ)句這樣寫:
select *
from #t1 A inner join #t2 B
on A.name=B.name collate Chinese_PRC_CI_AI_WS
二.排序規(guī)則簡(jiǎn)介:
什么叫排序規(guī)則呢?MS是這樣描述的:"在 Microsoft SQL Server 2000 中,
字符串的物理存儲(chǔ)由排序規(guī)則控制。排序規(guī)則指定表示每個(gè)字符的位模式以及存
儲(chǔ)和比較字符所使用的規(guī)則。"
在查詢分析器內(nèi)執(zhí)行下面語(yǔ)句,可以得到SQL SERVER支持的所有排序規(guī)則。
select * from ::fn_helpcollations()
排序規(guī)則名稱由兩部份構(gòu)成,前半部份是指本排序規(guī)則所支持的字符集。
如:
Chinese_PRC_CS_AI_WS
前半部份:指UNICODE字符集,Chinese_PRC_指針對(duì)大陸簡(jiǎn)體字UNICODE的排序規(guī)則。
排序規(guī)則的后半部份即后綴 含義:
_BIN 二進(jìn)制排序
_CI(CS) 是否區(qū)分大小寫,CI不區(qū)分,CS區(qū)分
_AI(AS) 是否區(qū)分重音,AI不區(qū)分,AS區(qū)分
_KI(KS) 是否區(qū)分假名類型,KI不區(qū)分,KS區(qū)分
_WI(WS) 是否區(qū)分寬度 WI不區(qū)分,WS區(qū)分
區(qū)分大小寫:如果想讓比較將大寫字母和小寫字母視為不等,請(qǐng)選擇該選項(xiàng)。
區(qū)分重音:如果想讓比較將重音和非重音字母視為不等,請(qǐng)選擇該選項(xiàng)。如果選擇該選項(xiàng),
比較還將重音不同的字母視為不等。
區(qū)分假名:如果想讓比較將片假名和平假名日語(yǔ)音節(jié)視為不等,請(qǐng)選擇該選項(xiàng)。
區(qū)分寬度:如果想讓比較將半角字符和全角字符視為不等,請(qǐng)選擇該選項(xiàng)
三.排序規(guī)則的應(yīng)用:
SQL SERVER提供了大量的WINDOWS和SQLSERVER專用的排序規(guī)則,但它的應(yīng)用往往
被開發(fā)人員所忽略。其實(shí)它在實(shí)踐中大有用處。
例1:讓表NAME列的內(nèi)容按拼音排序:
create table #t(id int,name varchar(20))
insert #t select 1,‘中‘
union all select 2,‘國(guó)‘
union all select 3,‘人‘
union all select 4,‘阿‘
select * from #t order by name collate Chinese_PRC_CS_AS_KS_WS
drop table #t
/*結(jié)果:
id name
----------- --------------------
4 阿
2 國(guó)
3 人
1 中
*/
例2:讓表NAME列的內(nèi)容按姓氏筆劃排序:
create table #t(id int,name varchar(20))
insert #t select 1,‘三‘
union all select 2,‘乙‘
union all select 3,‘二‘
union all select 4,‘一‘
union all select 5,‘十‘
select * from #t order by name collate Chinese_PRC_Stroke_CS_AS_KS_WS
drop table #t
/*結(jié)果:
id name
----------- --------------------
4 一
2 乙
3 二
5 十
1 三
*/
四.在實(shí)踐中排序規(guī)則應(yīng)用的擴(kuò)展
SQL SERVER漢字排序規(guī)則可以按拼音、筆劃等排序,那么我們?nèi)绾卫眠@種功能
來(lái)處理漢字的一些難題呢?我現(xiàn)在舉個(gè)例子:
用排序規(guī)則的特性計(jì)算漢字筆劃
要計(jì)算漢字筆劃,我們得先做準(zhǔn)備工作,我們知道,WINDOWS多國(guó)漢字,UNICODE目前
收錄漢字共20902個(gè)。簡(jiǎn)體GBK碼漢字UNICODE值從19968開始。
首先,我們先用SQLSERVER方法得到所有漢字,不用字典,我們簡(jiǎn)單利用SQL語(yǔ)句就
可以得到:
select top 20902 code=identity(int,19968,1) into #t from syscolumns a,syscolumns b
再用以下語(yǔ)句,我們就得到所有漢字,它是按UNICODE值排序的:
select code,nchar(code) as CNWord from #t
然后,我們用SELECT語(yǔ)句,讓它按筆劃排序。
select code,nchar(code) as CNWord
from #t
order by nchar(code) collate Chinese_PRC_Stroke_CS_AS_KS_WS,code
結(jié)果:
code CNWord
----------- ------
19968 一
20008 丨
20022 丶
20031 丿
20032 乀
20033 乁
20057 乙
20058 乚
20059 乛
20101 亅
19969 丁
..........
從上面的結(jié)果,我們可以清楚的看到,一筆的漢字,code是從19968到20101,從小到大排,但到
了二筆漢字的第一個(gè)字“丁”,CODE為19969,就不按順序而重新開始了。有了這結(jié)果,我們就可以輕
松的用SQL語(yǔ)句得到每種筆劃漢字歸類的第一個(gè)或最后一個(gè)漢字。
下面用語(yǔ)句得到最后一個(gè)漢字:
create table #t1(id int identity,code int,cnword nvarchar(2))
insert #t1(code,cnword)
select code,nchar(code) as CNWord from #t
order by nchar(code) collate Chinese_PRC_Stroke_CS_AS_KS_WS,code
select A.cnword
from #t1 A
left join #t1 B on A.id=B.id-1 and A.code<B.code
where B.code is null
order by A.id
得到36個(gè)漢字,每個(gè)漢字都是每種筆劃數(shù)按Chinese_PRC_Stroke_CS_AS_KS_WS排序規(guī)則排序后的
最后一個(gè)漢字:
亅阝馬風(fēng)龍齊龜齒鴆齔龕龂齠齦齪龍龠龎龐龑龡龢龝齹龣龥齈龞麷鸞麣龖龗齾齉龘
上面可以看出:“亅”是所有一筆漢字排序后的最后一個(gè)字,“阝”是所有二筆漢字排序后的最后
一個(gè)字......等等。
但同時(shí)也發(fā)現(xiàn),從第33個(gè)漢字“龗(33筆)”后面的筆劃有些亂,不正確。但沒(méi)關(guān)系,比“龗”筆劃
多的只有四個(gè)漢字,我們手工加上:齾35筆,齉36筆,靐39筆,龘64筆
建漢字筆劃表(TAB_HZBH):
create table tab_hzbh(id int identity,cnword nchar(1))
--先插入前33個(gè)漢字
insert tab_hzbh
select top 33 A.cnword
from #t1 A
left join #t1 B on A.id=B.id-1 and A.code<B.code
where B.code is null
order by A.id
--再加最后四個(gè)漢字
set identity_insert tab_hzbh on
go
insert tab_hzbh(id,cnword)
select 35,N‘齾‘
union all select 36,N‘齉‘
union all select 39,N‘靐‘
union all select 64,N‘龘‘
go
set identity_insert tab_hzbh off
go
到此為止,我們可以得到結(jié)果了,比如我們想得到漢字“國(guó)”的筆劃:
declare @a nchar(1)
set @a=‘國(guó)‘
select top 1 id
from tab_hzbh
where cnword>=@a collate Chinese_PRC_Stroke_CS_AS_KS_WS
order by id
id
-----------
8
(結(jié)果:漢字“國(guó)”筆劃數(shù)為8)
上面所有準(zhǔn)備過(guò)程,只是為了寫下面這個(gè)函數(shù),這個(gè)函數(shù)撇開上面建的所有臨時(shí)表和固
定表,為了通用和代碼轉(zhuǎn)移方便,把表tab_hzbh的內(nèi)容寫在語(yǔ)句內(nèi),然后計(jì)算用戶輸入一串
漢字的總筆劃:
create function fun_getbh(@str nvarchar(4000))
returns int
as
begin
declare @word nchar(1),@n int
set @n=0
while len(@str)>0
begin
set @word=left(@str,1)
--如果非漢字,筆劃當(dāng)0計(jì)
set @n=@n+(case when unicode(@word) between 19968 and 19968+20901
then (select top 1 id from (
select 1 as id,N‘亅‘ as word
union all select 2,N‘阝‘
union all select 3,N‘馬‘
union all select 4,N‘風(fēng)‘
union all select 5,N‘龍‘
union all select 6,N‘齊‘
union all select 7,N‘龜‘
union all select 8,N‘齒‘
union all select 9,N‘鴆‘
union all select 10,N‘齔‘
union all select 11,N‘龕‘
union all select 12,N‘龂‘
union all select 13,N‘齠‘
union all select 14,N‘齦‘
union all select 15,N‘齪‘
union all select 16,N‘龍‘
union all select 17,N‘龠‘
union all select 18,N‘龎‘
union all select 19,N‘龐‘
union all select 20,N‘龑‘
union all select 21,N‘龡‘
union all select 22,N‘龢‘
union all select 23,N‘龝‘
union all select 24,N‘齹‘
union all select 25,N‘龣‘
union all select 26,N‘龥‘
union all select 27,N‘齈‘
union all select 28,N‘龞‘
union all select 29,N‘麷‘
union all select 30,N‘鸞‘
union all select 31,N‘麣‘
union all select 32,N‘龖‘
union all select 33,N‘龗‘
union all select 35,N‘齾‘
union all select 36,N‘齉‘
union all select 39,N‘靐‘
union all select 64,N‘龘‘
) T
where word>=@word collate Chinese_PRC_Stroke_CS_AS_KS_WS
order by id ASC) else 0 end)
set @str=right(@str,len(@str)-1)
end
return @n
end
--函數(shù)調(diào)用實(shí)例:
select dbo.fun_getbh(‘中華人民共和國(guó)‘),dbo.fun_getbh(‘中華人民共和國(guó)‘)
執(zhí)行結(jié)果:筆劃總數(shù)分別為39和46,簡(jiǎn)繁體都行。
當(dāng)然,你也可以把上面“UNION ALL”內(nèi)的漢字和筆劃改存在固定表內(nèi),在漢字
列建CLUSTERED INDEX,列排序規(guī)則設(shè)定為:
Chinese_PRC_Stroke_CS_AS_KS_WS
這樣速度更快。如果你用的是BIG5碼的操作系統(tǒng),你得另外生成漢字,方法一樣。
但有一點(diǎn)要記?。哼@些漢字是通過(guò)SQL語(yǔ)句SELECT出來(lái)的,不是手工輸入的,更不
是查字典得來(lái)的,因?yàn)樾氯A字典畢竟不同于UNICODE字符集,查字典的結(jié)果會(huì)不正
確。
用排序規(guī)則的特性得到漢字拼音首字母
用得到筆劃總數(shù)相同的方法,我們也可以寫出求漢字拼音首字母的函數(shù)。如下:
create function fun_getPY(@str nvarchar(4000))
returns nvarchar(4000)
as
begin
declare @word nchar(1),@PY nvarchar(4000)
set @PY=‘‘
while len(@str)>0
begin
set @word=left(@str,1)
--如果非漢字字符,返回原字符
set @PY=@PY+(case when unicode(@word) between 19968 and 19968+20901
then (select top 1 PY from (
select ‘A‘ as PY,N‘驁‘ as word
union all select ‘B‘,N‘簿‘
union all select ‘C‘,N‘錯(cuò)‘
union all select ‘D‘,N‘鵽‘
union all select ‘E‘,N‘樲‘
union all select ‘F‘,N‘鰒‘
union all select ‘G‘,N‘腂‘
union all select ‘H‘,N‘夻‘
union all select ‘J‘,N‘?dāng)h‘
union all select ‘K‘,N‘穒‘
union all select ‘L‘,N‘鱳‘
union all select ‘M‘,N‘?dāng)妗?br>union all select ‘N‘,N‘桛‘
union all select ‘O‘,N‘漚‘
union all select ‘P‘,N‘曝‘
union all select ‘Q‘,N‘囕‘
union all select ‘R‘,N‘鶸‘
union all select ‘S‘,N‘蜶‘
union all select ‘T‘,N‘籜‘
union all select ‘W‘,N‘鶩‘
union all select ‘X‘,N‘鑂‘
union all select ‘Y‘,N‘韻‘
union all select ‘Z‘,N‘咗‘
) T
where word>=@word collate Chinese_PRC_CS_AS_KS_WS
order by PY ASC) else @word end)
set @str=right(@str,len(@str)-1)
end
return @PY
end
--函數(shù)調(diào)用實(shí)例:
select dbo.fun_getPY(‘中華人民共和國(guó)‘),dbo.fun_getPY(‘中華人民共和國(guó)‘)
結(jié)果都為:ZHRMGHG
你若有興趣,也可用相同的方法,擴(kuò)展為得到漢字全拼的函數(shù),甚至還可以得到全拼的讀
音聲調(diào),不過(guò)全拼分類大多了。得到全拼最好是用對(duì)照表,兩萬(wàn)多漢字搜索速度很快,用對(duì)照
表還可以充分利用表的索引。
排序規(guī)則還有很多其它的巧妙用法,限于篇幅在此就不再詳細(xì)說(shuō)明。歡迎大家共同探討。
==================================================================================================
如何實(shí)現(xiàn)對(duì)數(shù)據(jù)庫(kù)單個(gè)字段進(jìn)行加密 選擇自 callzjy 的 Blog
關(guān)鍵字 callzjy 字段加密 sqlserver 函數(shù)
出處
create view v_rand
as
select c=unicode(cast(round(rand()*255,0) as tinyint))
go
create function f_jmstr(@str varchar(8000),@type bit)returns varchar(8000)
/*
*參數(shù)說(shuō)明
*str:要加密的字符串或已經(jīng)加密后的字符
*type:操作類型--0加密--解密
*返回值說(shuō)明
*當(dāng)操作類型為加密時(shí)(type--0):返回為加密后的str,即存放于數(shù)據(jù)庫(kù)中的字符串
*當(dāng)操作類型為解密時(shí)(type--1):返回為實(shí)際字符串,即加密字符串解密后的原來(lái)字符串
*/
As
begin
declare @re varchar(8000)--返回值
declare @c int--加密字符
declare @i int
/*
*加密方法為原字符異或一個(gè)隨機(jī)ASCII字符
*/
if @type=0--加密
begin
select @c=c,@re=‘‘,@i=len(@str) from v_rand
while @i>0
select @re=nchar(unicode(substring(@str,@i,1))^@c^@i)+@re
,@i=@i-1
set @re=@re+nchar(@c)
end
else--解密
begin
select @i=len(@str)-1,@c=unicode(substring(@str,@i+1,1)),@re=‘‘
while @i>0
select @re=nchar(unicode(substring(@str,@i,1))^@c^@i)+@re ,@i=@i-1
end
return(@re)
end
go
--測(cè)試
declare @tempstr varchar(20)
set @tempstr=‘ 1 2 3aA‘
select dbo.f_jmstr(dbo.f_jmstr(@tempstr,0),1)
輸出結(jié)果
1 2 3aA
(完)
==================================================================================================
讓數(shù)據(jù)庫(kù)產(chǎn)生一張?jiān)敿?xì)的日歷表
也許有了這張表,你的工作會(huì)輕松很多!
CREATE TABLE [dbo].[time_dimension] (
[time_id] [int] IDENTITY (1, 1) NOT NULL ,
[the_date] [datetime] NULL ,
[the_day] [nvarchar] (15) NULL ,
[the_month] [nvarchar] (15) NULL ,
[the_year] [smallint] NULL ,
[day_of_month] [smallint] NULL ,
[week_of_year] [smallint] NULL ,
[month_of_year] [smallint] NULL ,
[quarter] [nvarchar] (2) NULL ,
[fiscal_period] [nvarchar] (20) NULL
) ON [PRIMARY]
DECLARE @WeekString varchar(12),
@dDate SMALLDATETIME,
@sMonth varchar(20),
@iYear smallint,
@iDayOfMonth smallint,
@iWeekOfYear smallint,
@iMonthOfYear smallint,
@sQuarter varchar(2),
@sSQL varchar(100),
@adddays int
SELECT @adddays = 1 --日期增量(可以自由設(shè)定)
SELECT @dDate = ‘01/01/2002‘ --開始日期
WHILE @dDate < ‘12/31/2004‘ --結(jié)束日期
BEGIN
SELECT @WeekString = DATENAME (dw, @dDate)
SELECT @sMonth=DATENAME(mm,@dDate)
SELECT @iYear= DATENAME (yy, @dDate)
SELECT @iDayOfMonth=DATENAME (dd, @dDate)
SELECT @iWeekOfYear= DATENAME (week, @dDate)
SELECT @iMonthOfYear=DATEPART(month, @dDate)
SELECT @sQuarter = ‘Q‘ + CAST(DATENAME (quarter, @dDate)as varchar(1))
INSERT INTO time_dimension(the_date, the_day, the_month, the_year,
day_of_month,
week_of_year, month_of_year, quarter) VALUES
(@dDate, @WeekString, @sMonth, @iYear, @iDayOfMonth, @iWeekOfYear,
@iMonthOfYear, @sQuarter)
SELECT @dDate = @dDate + @adddays
END
GO
select * from time_dimension
=================================================================================
--搜索某個(gè)字符串在那個(gè)表的那個(gè)字段中
declare @str varchar(100)
set @str=‘White‘ --要搜索的字符串
declare @s varchar(8000)
declare tb cursor local for
select s=‘if exists(select 1 from [‘+b.name+‘] where [‘+a.name+‘] like ‘‘%‘+@str+‘%‘‘)
print ‘‘所在的表及字段: [‘+b.name+‘].[‘+a.name+‘]‘‘‘
from syscolumns a join sysobjects b on a.id=b.id
where b.xtype=‘U‘ and a.status>=0
and a.xusertype in(175,239,231,167)
open tb
fetch next from tb into @s
while @@fetch_status=0
begin
exec(@s)
fetch next from tb into @s
end
close tb
deallocate tb
/*--測(cè)試結(jié)果
所在的表及字段: [authors].[au_lname]
--*/
======================================================================================
--查詢指定的表在那些數(shù)據(jù)庫(kù)中存在
declare @tbname sysname
set @tbname=‘客戶資料‘
declare @dbname sysname,@sql nvarchar(4000),@re bit,@sql1 varchar(8000)
set @sql1=‘‘
declare tb cursor for select name from master..sysdatabases
open tb
fetch next from tb into @dbname
while @@fetch_status=0
begin
set @sql=‘set @re=case when exists(select 1 from [‘
+@dbname+‘]..sysobjects where xtype=‘‘U‘‘ and name=‘‘‘
+@tbname+‘‘‘) then 1 else 0 end‘
exec sp_executesql @sql,N‘@re bit out‘,@re out
if @re=1 set @sql1=@sql1+‘ union all select ‘‘‘+@dbname+‘‘‘‘
fetch next from tb into @dbname
end
close tb
deallocate tb
set @sql1=substring(@sql1,12,8000)
exec(@sql1)
======================================================================================
比較兩個(gè)數(shù)據(jù)庫(kù)的表結(jié)構(gòu)差異 選擇自 zjcxc 的 Blog
關(guān)鍵字 表結(jié)構(gòu),差異
出處
/*--比較兩個(gè)數(shù)據(jù)庫(kù)的表結(jié)構(gòu)差異
--*/
/*--調(diào)用示例
exec p_comparestructure ‘xzkh_model‘,‘xzkh_new‘
--*/
if exists (select * from dbo.sysobjects where id = object_id(N‘[dbo].[p_comparestructure]‘) and OBJECTPROPERTY(id, N‘IsProcedure‘) = 1)
drop procedure [dbo].[p_comparestructure]
GO
create proc p_comparestructure
@dbname1 varchar(250), --要比較的數(shù)據(jù)庫(kù)名1
@dbname2 varchar(250) --要比較的數(shù)據(jù)庫(kù)名2
as
create table #tb1(表名1 varchar(250),字段名 varchar(250),序號(hào) int,標(biāo)識(shí) bit,主鍵 bit,類型 varchar(250),
占用字節(jié)數(shù) int,長(zhǎng)度 int,小數(shù)位數(shù) int,允許空 bit,默認(rèn)值 varchar(500),字段說(shuō)明 varchar(500))
create table #tb2(表名2 varchar(250),字段名 varchar(250),序號(hào) int,標(biāo)識(shí) bit,主鍵 bit,類型 varchar(250),
占用字節(jié)數(shù) int,長(zhǎng)度 int,小數(shù)位數(shù) int,允許空 bit,默認(rèn)值 varchar(500),字段說(shuō)明 varchar(500))
--得到數(shù)據(jù)庫(kù)1的結(jié)構(gòu)
exec(‘insert into #tb1 SELECT
表名=d.name,字段名=a.name,序號(hào)=a.colid,
標(biāo)識(shí)=case when a.status=0x80 then 1 else 0 end,
主鍵=case when exists(SELECT 1 FROM ‘+@dbname1+‘..sysobjects where xtype=‘‘PK‘‘ and name in (
SELECT name FROM ‘+@dbname1+‘..sysindexes WHERE indid in(
SELECT indid FROM ‘+@dbname1+‘..sysindexkeys WHERE id = a.id AND colid=a.colid
))) then 1 else 0 end,
類型=b.name, 占用字節(jié)數(shù)=a.length,長(zhǎng)度=a.prec,小數(shù)位數(shù)=a.scale, 允許空=a.isnullable,
默認(rèn)值=isnull(e.text,‘‘‘‘‘‘),字段說(shuō)明=isnull(g.[value],‘‘‘‘‘‘)
FROM ‘+@dbname1+‘..syscolumns a
left join ‘+@dbname1+‘..systypes b on a.xtype=b.xusertype
inner join ‘+@dbname1+‘..sysobjects d on a.id=d.id and d.xtype=‘‘U‘‘ and d.name<>‘‘dtproperties‘‘
left join ‘+@dbname1+‘..syscomments e on a.cdefault=e.id
left join ‘+@dbname1+‘..sysproperties g on a.id=g.id and a.colid=g.smallid
order by a.id,a.colorder‘)
--得到數(shù)據(jù)庫(kù)2的結(jié)構(gòu)
exec(‘insert into #tb2 SELECT
表名=d.name,字段名=a.name,序號(hào)=a.colid,
標(biāo)識(shí)=case when a.status=0x80 then 1 else 0 end,
主鍵=case when exists(SELECT 1 FROM ‘+@dbname2+‘..sysobjects where xtype=‘‘PK‘‘ and name in (
SELECT name FROM ‘+@dbname2+‘..sysindexes WHERE indid in(
SELECT indid FROM ‘+@dbname2+‘..sysindexkeys WHERE id = a.id AND colid=a.colid
))) then 1 else 0 end,
類型=b.name, 占用字節(jié)數(shù)=a.length,長(zhǎng)度=a.prec,小數(shù)位數(shù)=a.scale, 允許空=a.isnullable,
默認(rèn)值=isnull(e.text,‘‘‘‘‘‘),字段說(shuō)明=isnull(g.[value],‘‘‘‘‘‘)
FROM ‘+@dbname2+‘..syscolumns a
left join ‘+@dbname2+‘..systypes b on a.xtype=b.xusertype
inner join ‘+@dbname2+‘..sysobjects d on a.id=d.id and d.xtype=‘‘U‘‘ and d.name<>‘‘dtproperties‘‘
left join ‘+@dbname2+‘..syscomments e on a.cdefault=e.id
left join ‘+@dbname2+‘..sysproperties g on a.id=g.id and a.colid=g.smallid
order by a.id,a.colorder‘)
--and not exists(select 1 from #tb2 where 表名2=a.表名1)
select 比較結(jié)果=case when a.表名1 is null and b.序號(hào)=1 then ‘庫(kù)1缺少表:‘+b.表名2
when b.表名2 is null and a.序號(hào)=1 then ‘庫(kù)2缺少表:‘+a.表名1
when a.字段名 is null and exists(select 1 from #tb1 where 表名1=b.表名2) then ‘庫(kù)1 [‘+b.表名2+‘] 缺少字段:‘+b.字段名
when b.字段名 is null and exists(select 1 from #tb2 where 表名2=a.表名1) then ‘庫(kù)2 [‘+a.表名1+‘] 缺少字段:‘+a.字段名
when a.標(biāo)識(shí)<>b.標(biāo)識(shí) then ‘標(biāo)識(shí)不同‘
when a.主鍵<>b.主鍵 then ‘主鍵設(shè)置不同‘
when a.類型<>b.類型 then ‘字段類型不同‘
when a.占用字節(jié)數(shù)<>b.占用字節(jié)數(shù) then ‘占用字節(jié)數(shù)‘
when a.長(zhǎng)度<>b.長(zhǎng)度 then ‘長(zhǎng)度不同‘
when a.小數(shù)位數(shù)<>b.小數(shù)位數(shù) then ‘小數(shù)位數(shù)不同‘
when a.允許空<>b.允許空 then ‘是否允許空不同‘
when a.默認(rèn)值<>b.默認(rèn)值 then ‘默認(rèn)值不同‘
when a.字段說(shuō)明<>b.字段說(shuō)明 then ‘字段說(shuō)明不同‘
else ‘‘ end,
*
from #tb1 a
full join #tb2 b on a.表名1=b.表名2 and a.字段名=b.字段名
where a.表名1 is null or a.字段名 is null or b.表名2 is null or b.字段名 is null
or a.標(biāo)識(shí)<>b.標(biāo)識(shí) or a.主鍵<>b.主鍵 or a.類型<>b.類型
or a.占用字節(jié)數(shù)<>b.占用字節(jié)數(shù) or a.長(zhǎng)度<>b.長(zhǎng)度 or a.小數(shù)位數(shù)<>b.小數(shù)位數(shù)
or a.允許空<>b.允許空 or a.默認(rèn)值<>b.默認(rèn)值 or a.字段說(shuō)明<>b.字段說(shuō)明
order by isnull(a.表名1,b.表名2),isnull(a.序號(hào),b.序號(hào))--isnull(a.字段名,b.字段名)
go
==========================================================================================
行列轉(zhuǎn)換 交*表
出處
總結(jié)了一些有代表性的貼子,具體見http://expert.csdn.net/Expert/topic/2440/2440306.xml?temp=.6941645
1: 列轉(zhuǎn)為行:
eg1:
Create table test (name char(10),km char(10),cj int)
go
insert test values(‘張三‘,‘語(yǔ)文‘,80)
insert test values(‘張三‘,‘?dāng)?shù)學(xué)‘,86)
insert test values(‘張三‘,‘英語(yǔ)‘,75)
insert test values(‘李四‘,‘語(yǔ)文‘,78)
insert test values(‘李四‘,‘?dāng)?shù)學(xué)‘,85)
insert test values(‘李四‘,‘英語(yǔ)‘,78)
想變成
姓名 語(yǔ)文 數(shù)學(xué) 英語(yǔ)
張三 80 86 75
李四 78 85 78
declare @sql varchar(8000)
set @sql = ‘select name‘
select @sql = @sql + ‘,sum(case km when ‘‘‘+km+‘‘‘ then cj end) [‘+km+‘]‘
from (select distinct km from test) as a
select @sql = @sql+‘ from test group by name‘
exec(@sql)
drop table test
eg2:
有表A,
id pid
1 1
1 2
1 3
2 1
2 2
3 1
如何化成表B:
id pid
1 1,2,3
2 1,2
3 1
或者是從表B變成A(不要用游標(biāo))
以前有相似的列子,現(xiàn)在找不到了,幫幫忙!
--1.創(chuàng)建一個(gè)合并的函數(shù)
create function fmerg(@id int)
returns varchar(8000)
as
begin
declare @str varchar(8000)
set @str=‘‘
select @str=@str+‘,‘+cast(pid as varchar) from 表A where id=@id
set @str=right(@str,len(@str)-1)
return(@str)
End
go
--調(diào)用自定義函數(shù)得到結(jié)果
select distinct id,dbo.fmerg(id) from 表A
2:
/*********** 行轉(zhuǎn)列 *****************/
測(cè)試:
create table t1 (a int,b int,c int,d int,e int,f int,g int,h int)
insert t1 values(15, 9, 1, 0, 1, 2, 2, 0)
declare @ varchar(8000)
set @=‘‘
select @=@+rtrim(name)+‘ from t1 union all select ‘ from syscolumns where id=object_id(‘t1‘)
set @=left(@,len(@)-len(‘ from t1 union all select ‘))
--print @
exec(‘select ‘+@+‘ from t1‘)
a
-----------
15
9
1
0
1
2
2
0
====================================================================================================
動(dòng)態(tài)SQL語(yǔ)句 選擇自 txlicenhe 的 Blog
關(guān)鍵字 動(dòng)態(tài)SQL EXEC SP_EXECUTESQL
出處
1:
普通SQL語(yǔ)句可以用Exec執(zhí)行
eg: Select * from tableName
Exec(‘select * from tableName‘)
sp_executesql N‘select * from tableName‘ -- 請(qǐng)注意字符串前一定要加N
2:
字段名,表名,數(shù)據(jù)庫(kù)名之類作為變量時(shí),必須用動(dòng)態(tài)SQL
eg:
declare @fname varchar(20)
set @fname = ‘[name]‘
Select @fname from sysobjects -- 錯(cuò)誤
Exec(‘select ‘ + @fname + ‘ from sysobjects‘) -- 請(qǐng)注意 加號(hào)前后的 單引號(hào)的邊上要加空格
exec sp_executesql N‘ select ‘ + @fname + ‘ from sysobjects‘
當(dāng)然將字符串改成變量的形式也可
declare @s varchar(1000)
set @s = ‘select ‘ + @fname + ‘ from sysobjects‘
Exec(@s) -- 成功
exec sp_executesql @s -- 此句會(huì)報(bào)錯(cuò)
declare @s Nvarchar(1000) -- 注意此處改為nvarchar(1000)
set @s = ‘select ‘ + @fname + ‘ from sysobjects‘
Exec(@s) -- 成功
exec sp_executesql @s -- 此句正確,
3: 輸出參數(shù)
eg:
declare @num,
@sqls
set @sqls=‘select count(*) from ‘ + @servername + ‘.a.dbo.b‘
exec(@sqls)
我如何能將exec執(zhí)行的結(jié)果存入變量@num中
declare @num int,
@sqls nvarchar(4000)
set @sqls=‘select @a=count(*) from ‘+@servername+‘.a.dbo.b‘
exec sp_executesql @sqls,N‘@a int output‘,@num output
select @num
=========================================================================================
介紹取一表前N筆記錄的各種數(shù)據(jù)庫(kù)的寫法...
作者﹕CCBZZP
1. ORACLE
SELECT * FROM TABLE1 WHERE ROWNUM<=N
2. INFORMIX
SELECT FIRST N * FROM TABLE1
3. DB2
SELECT * ROW_NUMBER() OVER(ORDER BY COL1 DESC) AS ROWNUM WHERE ROWNUM<=N
或者
SELECT COLUMN FROM TABLE FETCH FIRST N ROWS ONLY
4. SQL SERVER
SELECT TOP N * FROM TABLE1
5. SYBASE
SET ROWCOUNT N
GO
SELECT * FROM TABLE1
6. MYSQL
SELECT * FROM TABLE1 LIMIT N
7. FOXPRO
SELECT * TOP N FROM TABLE ORDER BY COLUMN
===================================================================================
create procedure SP_GET_TABLE_INFO
@ObjName varchar(128) /* The table to generate sql script */
as
declare @Script varchar(255)
declare @ColName varchar(30)
declare @ColID TinyInt
declare @UserType smallint
declare @TypeName sysname
declare @Length TinyInt
declare @Prec TinyInt
declare @Scale TinyInt
declare @Status TinyInt
declare @cDefault int
declare @DefaultID TinyInt
declare @Const_Key varchar(255)
declare @IndID SmallInt
declare @IndStatus Int
declare @Index_Key varchar(255)
declare @DBName varchar(30)
declare @strPri_Key varchar (255)
/*
** Check to see the the table exists and initialize @objid.
*/
if not Exists(Select name from sysobjects where name = @ObjName)
begin
select @DBName = db_name()
raiserror(15009,-1,-1,@ObjName,@DBName)
return (1)
end
create table #spscript
(
id int IDENTITY not null,
Script Varchar(255) NOT NULL,
LastLine tinyint
)
declare Cursor_Column INSENSITIVE CURSOR
for Select a.name,a.ColID,a.usertype,b.name,a.length,a.prec,a.scale,a.Status, a.cDefault,
case a.cdefault when 0 then ‘ ‘ else (select c.Text from syscomments c where a.cdefault = c.id) end const_key
from syscolumns a, systypes b where object_name(a.id) = @ObjName
and a.usertype = b.usertype order by a.ColID
set nocount on
Select @Script = ‘Create table ‘ + @ObjName + ‘(‘
Insert into #spscript values(@Script,0)
/* Get column information */
open Cursor_Column
fetch next from Cursor_Column into @ColName,@ColID,@UserType,@TypeName,@Length,@Prec,@Scale,
@Status,@cDefault,@Const_Key
Select @Script = ‘‘
while (@@FETCH_STATUS <> -1)
begin
if (@@FETCH_STATUS <> -2)
begin
Select @Script = @ColName + ‘ ‘ + @TypeName
if @UserType in (1,2,3,4)
Select @Script = @Script + ‘(‘ + Convert(char(3),@Length) + ‘) ‘
else if @UserType in (24)
Select @Script = @Script + ‘(‘ + Convert(char(3),@Prec) + ‘,‘
+ Convert(char(3),@Scale) + ‘) ‘
else
Select @Script = @Script + ‘ ‘
if ( @Status & 0x80 ) > 0
Select @Script = @Script + ‘ IDENTITY(1,1) ‘
if ( @Status & 0x08 ) > 0
Select @Script = @Script + ‘ NULL ‘
else
Select @Script = @Script + ‘ NOT NULL ‘
if @cDefault > 0
Select @Script = @Script + ‘ DEFAULT ‘ + @Const_Key
end
fetch next from Cursor_Column into @ColName,@ColID,@UserType,@TypeName,@Length,@Prec,@Scale,
@Status,@cDefault,@Const_Key
if @@FETCH_STATUS = 0
begin
Select @Script = @Script + ‘,‘
Insert into #spscript values(@Script,0)
end
else
begin
Insert into #spscript values(@Script,1)
Insert into #spscript values(‘)‘,0)
end
end
Close Cursor_Column
Deallocate Cursor_Column
/* Get index information */
Declare Cursor_Index INSENSITIVE CURSOR
for Select name,IndID,status from sysindexes where object_name(id)=@ObjName
and IndID > 0 and IndID<>255 order by IndID /*增加了對(duì)InDid為255的判斷*/
Open Cursor_Index
Fetch Next from Cursor_Index into @ColName, @IndID, @IndStatus
while (@@FETCH_STATUS <> -1)
begin
if @@FETCH_STATUS <> -2
begin
declare @i TinyInt
declare @thiskey varchar(50)
declare @IndDesc varchar(68) /* string to build up index desc in */
Select @i = 1
while (@i <= 16)
begin
select @thiskey = index_col(@ObjName, @IndID, @i)
if @thiskey is null
break
if @i = 1
select @Index_Key = index_col(@ObjName, @IndID, @i)
else
select @Index_Key = @Index_Key + ‘, ‘ + index_col(@ObjName, @IndID, @i)
select @i = @i + 1
end
if (@IndStatus & 0x02) > 0
Select @Script = ‘Create unique ‘
else
Select @Script = ‘Create ‘
if @IndID = 1
select @Script = @Script + ‘ clustered ‘
if (@IndStatus & 0x800) > 0
select @strPri_Key = ‘ PRIMARY KEY (‘ + @Index_Key + ‘)‘
else
select @strPri_Key = ‘‘
if @IndID > 1
select @Script = @Script + ‘ nonclustered ‘
Select @Script = @Script + ‘ index ‘ + @ColName + ‘ ON ‘+ @ObjName
+ ‘(‘ + @Index_Key + ‘)‘
Select @IndDesc = ‘‘
/*
** See if the index is ignore_dupkey (0x01).
*/
if @IndStatus & 0x01 = 0x01
Select @IndDesc = @IndDesc + ‘ IGNORE_DUP_KEY‘ + ‘,‘
/*
** See if the index is ignore_dup_row (0x04).
*/
/* if @IndStatus & 0x04 = 0x04 */
/* Select @IndDesc = @IndDesc + ‘ IGNORE_DUP_ROW‘ + ‘,‘ */ /* 2000 不在支持*/
/*
** See if the index is allow_dup_row (0x40).
*/
if @IndStatus & 0x40 = 0x40
Select @IndDesc = @IndDesc + ‘ ALLOW_DUP_ROW‘ + ‘,‘
if @IndDesc <> ‘‘
begin
Select @IndDesc = SubString( @IndDesc, 1, DataLength(@IndDesc) - 1 )
Select @Script = @Script + ‘ WITH ‘ + @IndDesc
end
/*
** Add the location of the data.
*/
end
if (@strPri_Key = ‘‘)
Insert into #spscript values(@Script,0)
else
update #spscript set Script = Script + @strPri_Key where LastLine = 1
Fetch Next from Cursor_Index into @ColName, @IndID, @IndStatus
end
Close Cursor_Index
Deallocate Cursor_Index
Select Script from #spscript
set nocount off
return (0)
==============================================================================================
收藏幾段SQL Server語(yǔ)句和存儲(chǔ)過(guò)程
-- ======================================================
--列出SQL SERVER 所有表,字段名,主鍵,類型,長(zhǎng)度,小數(shù)位數(shù)等信息
--在查詢分析器里運(yùn)行即可,可以生成一個(gè)表,導(dǎo)出到EXCEL中
-- ======================================================
SELECT
(case when a.colorder=1 then d.name else ‘‘ end)表名,
a.colorder 字段序號(hào),
a.name 字段名,
(case when COLUMNPROPERTY( a.id,a.name,‘IsIdentity‘)=1 then ‘√‘else ‘‘ end) 標(biāo)識(shí),
(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) 主鍵,
b.name 類型,
a.length 占用字節(jié)數(shù),
COLUMNPROPERTY(a.id,a.name,‘PRECISION‘) as 長(zhǎng)度,
isnull(COLUMNPROPERTY(a.id,a.name,‘Scale‘),0) as 小數(shù)位數(shù),
(case when a.isnullable=1 then ‘√‘else ‘‘ end) 允許空,
isnull(e.text,‘‘) 默認(rèn)值,
isnull(g.[value],‘‘) AS 字段說(shuō)明
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 a.id,a.colorder
-------------------------------------------------------------------------------------------------
列出SQL SERVER 所有表、字段定義,類型,長(zhǎng)度,一個(gè)值等信息
并導(dǎo)出到Excel 中
-- -- Export all user tables definition and one sample value
-- jan-13-2003,Dr.Zhang
-- 在查詢分析器里運(yùn)行:
SET ANSI_NULLS OFF
GO
SET NOCOUNT ON
GO
SET LANGUAGE ‘Simplified Chinese‘
go
DECLARE @tbl nvarchar(200),@fld nvarchar(200),@sql nvarchar(4000),@maxlen int,@sample nvarchar(40)
SELECT d.name TableName,a.name FieldName,b.name TypeName,a.length Length,a.isnullable IS_NULL INTO #t
FROM syscolumns a, systypes b,sysobjects d
WHERE a.xtype=b.xusertype and a.id=d.id and d.xtype=‘U‘
DECLARE read_cursor CURSOR
FOR SELECT TableName,FieldName FROM #t
SELECT TOP 1 ‘_TableName ‘ TableName,
‘FieldName ‘ FieldName,‘TypeName ‘ TypeName,
‘Length‘ Length,‘IS_NULL‘ IS_NULL,
‘MaxLenUsed‘ AS MaxLenUsed,‘Sample Value ‘ Sample,
‘Comment ‘ Comment INTO #tc FROM #t
OPEN read_cursor
FETCH NEXT FROM read_cursor INTO @tbl,@fld
WHILE (@@fetch_status <> -1) --- failes
BEGIN
IF (@@fetch_status <> -2) -- Missing
BEGIN
SET @sql=N‘SET @maxlen=(SELECT max(len(cast(‘+@fld+‘ as nvarchar))) FROM ‘+@tbl+‘)‘
--PRINT @sql
EXEC SP_EXECUTESQL @sql,N‘@maxlen int OUTPUT‘,@maxlen OUTPUT
--print @maxlen
SET @sql=N‘SET @sample=(SELECT TOP 1 cast(‘+@fld+‘ as nvarchar) FROM ‘+@tbl+‘ WHERE len(cast(‘+@fld+‘ as nvarchar))=‘+convert(nvarchar(5),@maxlen)+‘)‘
EXEC SP_EXECUTESQL @sql,N‘@sample varchar(30) OUTPUT‘,@sample OUTPUT
--for quickly
--SET @sql=N‘SET @sample=convert(varchar(20),(SELECT TOP 1 ‘+@fld+‘ FROM ‘+
--@tbl+‘ order by 1 desc ))‘
PRINT @sql
print @sample
print @tbl
EXEC SP_EXECUTESQL @sql,N‘@sample nvarchar(30) OUTPUT‘,@sample OUTPUT
INSERT INTO #tc SELECT *,ltrim(ISNULL(@maxlen,0)) as MaxLenUsed,
convert(nchar(20),ltrim(ISNULL(@sample,‘ ‘))) as Sample,‘ ‘ Comment FROM #t where TableName=@tbl and FieldName=@fld
END
FETCH NEXT FROM read_cursor INTO @tbl,@fld
END
CLOSE read_cursor
DEALLOCATE read_cursor
GO
SET ANSI_NULLS ON
GO
SET NOCOUNT OFF
GO
select count(*) from #t
DROP TABLE #t
GO
select count(*)-1 from #tc
select * into ##tx from #tc order by tablename
DROP TABLE #tc
--select * from ##tx
declare @db nvarchar(60),@sql nvarchar(3000)
set @db=db_name()
--請(qǐng)修改用戶名和口令 導(dǎo)出到Excel 中
set @sql=‘exec master.dbo.xp_cmdshell ‘‘bcp ..dbo.##tx out c:\‘+@db+‘_exp.xls -w -C936 -Usa -Psa ‘‘‘
print @sql
exec(@sql)
GO
DROP TABLE ##tx
GO
-- 根據(jù)表中數(shù)據(jù)生成insert語(yǔ)句的存儲(chǔ)過(guò)程
--建立存儲(chǔ)過(guò)程,執(zhí)行 spGenInsertSQL 表名
--感謝playyuer
-- CREATE proc spGenInsertSQL (@tablename varchar(256))
as
begin
declare @sql varchar(8000)
declare @sqlValues varchar(8000)
set @sql =‘ (‘
set @sqlValues = ‘values (‘‘+‘
select @sqlValues = @sqlValues + cols + ‘ + ‘‘,‘‘ + ‘ ,@sql = @sql + ‘[‘ + name + ‘],‘
from
(select case
when xtype in (48,52,56,59,60,62,104,106,108,122,127)
then ‘case when ‘+ name +‘ is null then ‘‘NULL‘‘ else ‘ + ‘cast(‘+ name + ‘ as varchar)‘+‘ end‘
when xtype in (58,61)
then ‘case when ‘+ name +‘ is null then ‘‘NULL‘‘ else ‘+‘‘‘‘‘‘‘‘‘ + ‘ + ‘cast(‘+ name +‘ as varchar)‘+ ‘+‘‘‘‘‘‘‘‘‘+‘ end‘
when xtype in (167)
then ‘case when ‘+ name +‘ is null then ‘‘NULL‘‘ else ‘+‘‘‘‘‘‘‘‘‘ + ‘ + ‘replace(‘+ name+‘,‘‘‘‘‘‘‘‘,‘‘‘‘‘‘‘‘‘‘‘‘)‘ + ‘+‘‘‘‘‘‘‘‘‘+‘ end‘
when xtype in (231)
then ‘case when ‘+ name +‘ is null then ‘‘NULL‘‘ else ‘+‘‘‘N‘‘‘‘‘‘ + ‘ + ‘replace(‘+ name+‘,‘‘‘‘‘‘‘‘,‘‘‘‘‘‘‘‘‘‘‘‘)‘ + ‘+‘‘‘‘‘‘‘‘‘+‘ end‘
when xtype in (175)
then ‘case when ‘+ name +‘ is null then ‘‘NULL‘‘ else ‘+‘‘‘‘‘‘‘‘‘ + ‘ + ‘cast(replace(‘+ name+‘,‘‘‘‘‘‘‘‘,‘‘‘‘‘‘‘‘‘‘‘‘) as Char(‘ + cast(length as varchar) + ‘))+‘‘‘‘‘‘‘‘‘+‘ end‘
when xtype in (239)
then ‘case when ‘+ name +‘ is null then ‘‘NULL‘‘ else ‘+‘‘‘N‘‘‘‘‘‘ + ‘ + ‘cast(replace(‘+ name+‘,‘‘‘‘‘‘‘‘,‘‘‘‘‘‘‘‘‘‘‘‘) as Char(‘ + cast(length as varchar) + ‘))+‘‘‘‘‘‘‘‘‘+‘ end‘
else ‘‘‘NULL‘‘‘
end as Cols,name
from syscolumns
where id = object_id(@tablename)
) T
set @sql =‘select ‘‘INSERT INTO [‘+ @tablename + ‘]‘ + left(@sql,len(@sql)-1)+‘) ‘ + left(@sqlValues,len(@sqlValues)-4) + ‘)‘‘ from ‘+@tablename
--print @sql
exec (@sql)
end
GO
-- --根據(jù)表中數(shù)據(jù)生成insert語(yǔ)句的存儲(chǔ)過(guò)程
--建立存儲(chǔ)過(guò)程,執(zhí)行 proc_insert 表名
--感謝Sky_blue
--
CREATE proc proc_insert (@tablename varchar(256))
as
begin
set nocount on
declare @sqlstr varchar(4000)
declare @sqlstr1 varchar(4000)
declare @sqlstr2 varchar(4000)
select @sqlstr=‘select ‘‘insert ‘+@tablename
select @sqlstr1=‘‘
select @sqlstr2=‘ (‘
select @sqlstr1= ‘ values ( ‘‘+‘
select @sqlstr1=@sqlstr1+col+‘+‘‘,‘‘+‘ ,@sqlstr2=@sqlstr2+name +‘,‘ from (select case
-- when a.xtype =173 then ‘case when ‘+a.name+‘ is null then ‘‘NULL‘‘ else ‘+‘convert(varchar(‘+convert(varchar(4),a.length*2+2)+‘),‘+a.name +‘)‘+‘ end‘
when a.xtype =104 then ‘case when ‘+a.name+‘ is null then ‘‘NULL‘‘ else ‘+‘convert(varchar(1),‘+a.name +‘)‘+‘ end‘
when a.xtype =175 then ‘case when ‘+a.name+‘ is null then ‘‘NULL‘‘ else ‘+‘‘‘‘‘‘‘‘‘+‘+‘replace(‘+a.name+‘,‘‘‘‘‘‘‘‘,‘‘‘‘‘‘‘‘‘‘‘‘)‘ + ‘+‘‘‘‘‘‘‘‘‘+‘ end‘
when a.xtype =61 then ‘case when ‘+a.name+‘ is null then ‘‘NULL‘‘ else ‘+‘‘‘‘‘‘‘‘‘+‘+‘convert(varchar(23),‘+a.name +‘,121)‘+ ‘+‘‘‘‘‘‘‘‘‘+‘ end‘
when a.xtype =106 then ‘case when ‘+a.name+‘ is null then ‘‘NULL‘‘ else ‘+‘convert(varchar(‘+convert(varchar(4),a.xprec+2)+‘),‘+a.name +‘)‘+‘ end‘
when a.xtype =62 then ‘case when ‘+a.name+‘ is null then ‘‘NULL‘‘ else ‘+‘convert(varchar(23),‘+a.name +‘,2)‘+‘ end‘
when a.xtype =56 then ‘case when ‘+a.name+‘ is null then ‘‘NULL‘‘ else ‘+‘convert(varchar(11),‘+a.name +‘)‘+‘ end‘
when a.xtype =60 then ‘case when ‘+a.name+‘ is null then ‘‘NULL‘‘ else ‘+‘convert(varchar(22),‘+a.name +‘)‘+‘ end‘
when a.xtype =239 then ‘case when ‘+a.name+‘ is null then ‘‘NULL‘‘ else ‘+‘‘‘‘‘‘‘‘‘+‘+‘replace(‘+a.name+‘,‘‘‘‘‘‘‘‘,‘‘‘‘‘‘‘‘‘‘‘‘)‘ + ‘+‘‘‘‘‘‘‘‘‘+‘ end‘
when a.xtype =108 then ‘case when ‘+a.name+‘ is null then ‘‘NULL‘‘ else ‘+‘convert(varchar(‘+convert(varchar(4),a.xprec+2)+‘),‘+a.name +‘)‘+‘ end‘
when a.xtype =231 then ‘case when ‘+a.name+‘ is null then ‘‘NULL‘‘ else ‘+‘‘‘‘‘‘‘‘‘+‘+‘replace(‘+a.name+‘,‘‘‘‘‘‘‘‘,‘‘‘‘‘‘‘‘‘‘‘‘)‘ + ‘+‘‘‘‘‘‘‘‘‘+‘ end‘
when a.xtype =59 then ‘case when ‘+a.name+‘ is null then ‘‘NULL‘‘ else ‘+‘convert(varchar(23),‘+a.name +‘,2)‘+‘ end‘
when a.xtype =58 then ‘case when ‘+a.name+‘ is null then ‘‘NULL‘‘ else ‘+‘‘‘‘‘‘‘‘‘+‘+‘convert(varchar(23),‘+a.name +‘,121)‘+ ‘+‘‘‘‘‘‘‘‘‘+‘ end‘
when a.xtype =52 then ‘case when ‘+a.name+‘ is null then ‘‘NULL‘‘ else ‘+‘convert(varchar(12),‘+a.name +‘)‘+‘ end‘
when a.xtype =122 then ‘case when ‘+a.name+‘ is null then ‘‘NULL‘‘ else ‘+‘convert(varchar(22),‘+a.name +‘)‘+‘ end‘
when a.xtype =48 then ‘case when ‘+a.name+‘ is null then ‘‘NULL‘‘ else ‘+‘convert(varchar(6),‘+a.name +‘)‘+‘ end‘
-- when a.xtype =165 then ‘case when ‘+a.name+‘ is null then ‘‘NULL‘‘ else ‘+‘convert(varchar(‘+convert(varchar(4),a.length*2+2)+‘),‘+a.name +‘)‘+‘ end‘
when a.xtype =167 then ‘case when ‘+a.name+‘ is null then ‘‘NULL‘‘ else ‘+‘‘‘‘‘‘‘‘‘+‘+‘replace(‘+a.name+‘,‘‘‘‘‘‘‘‘,‘‘‘‘‘‘‘‘‘‘‘‘)‘ + ‘+‘‘‘‘‘‘‘‘‘+‘ end‘
else ‘‘‘NULL‘‘‘
end as col,a.colid,a.name
from syscolumns a where a.id = object_id(@tablename) and a.xtype <>189 and a.xtype <>34 and a.xtype <>35 and a.xtype <>36
)t order by colid
select @sqlstr=@sqlstr+left(@sqlstr2,len(@sqlstr2)-1)+‘) ‘+left(@sqlstr1,len(@sqlstr1)-3)+‘)‘‘ from ‘+@tablename
-- print @sqlstr
exec( @sqlstr)
set nocount off
end
GO
說(shuō)明:本貼純屬收藏,目的在于大家交流,在此對(duì)作者表示感謝!
==========================================================================================
小寫轉(zhuǎn)大寫金額 選擇自 webmin 的 Blog
關(guān)鍵字 金額 SQL Server
出處
在網(wǎng)上見到一個(gè)Oracle的版本的小寫轉(zhuǎn)大寫金額的函數(shù),感覺(jué)還不錯(cuò)現(xiàn)在把它轉(zhuǎn)成SQL Server版本。
/********************************************************
作者:(birdie_7761@cmmail.com)
版本:1.0
創(chuàng)建時(shí)間:20020227
修改時(shí)間:
功能:小寫金額轉(zhuǎn)換成大寫
參數(shù):n_LowerMoney 小寫金額
v_TransType 種類 -- 1: directly translate, 0: read it in words
輸出:大寫金額
********************************************************/
CREATE FUNCTION dbo.L2U (@n_LowerMoney numeric(15,2),@v_TransType int)
RETURNS VARCHAR(200) AS
BEGIN
Declare @v_LowerStr VARCHAR(200) -- 小寫金額
Declare @v_UpperPart VARCHAR(200)
Declare @v_UpperStr VARCHAR(200) -- 大寫金額
Declare @i_I int
set @v_LowerStr = LTRIM(RTRIM(ROUND(@n_LowerMoney,2))) --四舍五入為指定的精度并刪除數(shù)據(jù)左右空格
set @i_I = 1
set @v_UpperStr = ‘‘
while ( @i_I <= len(@v_LowerStr))
begin
select @v_UpperPart = case substring(@v_LowerStr,len(@v_LowerStr) - @i_I + 1,1)
WHEN ‘.‘ THEN ‘元‘
WHEN ‘0‘ THEN ‘零‘
WHEN ‘1‘ THEN ‘壹‘
WHEN ‘2‘ THEN ‘貳‘
WHEN ‘3‘ THEN ‘叁‘
WHEN ‘4‘ THEN ‘肆‘
WHEN ‘5‘ THEN ‘伍‘
WHEN ‘6‘ THEN ‘陸‘
WHEN ‘7‘ THEN ‘柒‘
WHEN ‘8‘ THEN ‘捌‘
WHEN ‘9‘ THEN ‘玖‘
END
+
case @i_I
WHEN 1 THEN ‘分‘
WHEN 2 THEN ‘角‘
WHEN 3 THEN ‘‘
WHEN 4 THEN ‘‘
WHEN 5 THEN ‘拾‘
WHEN 6 THEN ‘佰‘
WHEN 7 THEN ‘仟‘
WHEN 8 THEN ‘萬(wàn)‘
WHEN 9 THEN ‘拾‘
WHEN 10 THEN ‘佰‘
WHEN 11 THEN ‘仟‘
WHEN 12 THEN ‘億‘
WHEN 13 THEN ‘拾‘
WHEN 14 THEN ‘佰‘
WHEN 15 THEN ‘仟‘
WHEN 16 THEN ‘萬(wàn)‘
ELSE ‘‘
END
set @v_UpperStr = @v_UpperPart + @v_UpperStr
set @i_I = @i_I + 1
end
if ( 0 = @v_TransType)
begin
set @v_UpperStr = REPLACE(@v_UpperStr,‘零拾‘,‘零‘)
set @v_UpperStr = REPLACE(@v_UpperStr,‘零佰‘,‘零‘)
set @v_UpperStr = REPLACE(@v_UpperStr,‘零仟‘,‘零‘)
set @v_UpperStr = REPLACE(@v_UpperStr,‘零零零‘,‘零‘)
set @v_UpperStr = REPLACE(@v_UpperStr,‘零零‘,‘零‘)
set @v_UpperStr = REPLACE(@v_UpperStr,‘零角零分‘,‘整‘)
set @v_UpperStr = REPLACE(@v_UpperStr,‘零分‘,‘整‘)
set @v_UpperStr = REPLACE(@v_UpperStr,‘零角‘,‘零‘)
set @v_UpperStr = REPLACE(@v_UpperStr,‘零億零萬(wàn)零元‘,‘億元‘)
set @v_UpperStr = REPLACE(@v_UpperStr,‘億零萬(wàn)零元‘,‘億元‘)
set @v_UpperStr = REPLACE(@v_UpperStr,‘零億零萬(wàn)‘,‘億‘)
set @v_UpperStr = REPLACE(@v_UpperStr,‘零萬(wàn)零元‘,‘萬(wàn)元‘)
set @v_UpperStr = REPLACE(@v_UpperStr,‘萬(wàn)零元‘,‘萬(wàn)元‘)
set @v_UpperStr = REPLACE(@v_UpperStr,‘零億‘,‘億‘)
set @v_UpperStr = REPLACE(@v_UpperStr,‘零萬(wàn)‘,‘萬(wàn)‘)
set @v_UpperStr = REPLACE(@v_UpperStr,‘零元‘,‘元‘)
set @v_UpperStr = REPLACE(@v_UpperStr,‘零零‘,‘零‘)
end
-- 對(duì)壹元以下的金額的處理
if ( ‘元‘ = substring(@v_UpperStr,1,1))
begin
set @v_UpperStr = substring(@v_UpperStr,2,(len(@v_UpperStr) - 1))
end
if ( ‘零‘ = substring(@v_UpperStr,1,1))
begin
set @v_UpperStr = substring(@v_UpperStr,2,(len(@v_UpperStr) - 1))
end
if ( ‘角‘ = substring(@v_UpperStr,1,1))
begin
set @v_UpperStr = substring(@v_UpperStr,2,(len(@v_UpperStr) - 1))
end
if ( ‘分‘ = substring(@v_UpperStr,1,1))
begin
set @v_UpperStr = substring(@v_UpperStr,2,(len(@v_UpperStr) - 1))
end
if (‘整‘ = substring(@v_UpperStr,1,1))
begin
set @v_UpperStr = ‘零元整‘
end
return @v_UpperStr
END
例子:
select dbo.L2U(56588441.111,0)
select dbo.L2U(00.00,0)
聯(lián)系客服