日期:2014-05-17  浏览次数:20350 次

-------1.关于master..spt_values的应用帖子----------

/**
最近在CSDN上见到很多关于master..spt_values的应用,感觉这个东西太好用了,
所以搜索了很多关于这方面的应用。
在此贴上自己的总结结果,希望各路大神批评指教,也希望大家继续把这方面的应用贴上。
*/

select number from master..spt_values with(nolock) where type='P'
/**解释:master..spt_values表的字段值为P的对应number字段值是从0-2047*/

-----------
--1.将字符串转换为列显示
if object_id('tb') is not null drop table tb
go
create table tb([编号] varchar(3),[产品] varchar(2),[数量] int,[单价] int,[金额] int,[序列号] varchar(8))
insert into tb([编号],[产品],[数量],[单价],[金额],[序列号])
select '001','AA',3,5,15,'12,13,14' union all
select '002','BB',8,9,13,'22,23,24'
go
select [编号],[产品],[数量],[单价],[金额]
,substring([序列号],b.number,charindex(',',[序列号]+',',b.number)-b.number) as [序列号]
from tb a with(nolock),master..spt_values b with(nolock)
where b.number>=1 and b.number<len(a.[序列号]) and b.type='P'
and substring(','+[序列号],number,1)=','
go
drop table tb
go
/**
编号   产品   数量          单价          金额          序列号
---- ---- ----------- ----------- ----------- --------
001  AA   3           5           15          12
001  AA   3           5           15          13
001  AA   3           5           15          14
002  BB   8           9           13          22
002  BB   8           9           13          23
002  BB   8           9           13          24
*/

----------
--2.第四个逗号之前的字符串
declare @str varchar(100)
set @str='10,102,10254,103265,541,2154,41,156'
;with cte as(
select left(@str,number-1) as ss,row_number()over(order by getdate()) as xh
from master..spt_values with(nolock) 
where number>=1 and number<=len(@str+',') and type='P' 
and substring(@str+',',number,1)=','
)select ss from cte where xh=4
/**
ss
-------------------
10,102,10254,103265
*/

----------
--3.找出两句话中相同的汉字
declare @Lctext1 varchar(100)
declare @Lctext2 varchar(100)
set @Lctext1='我们都是来自五湖四海的朋友'
set @Lctext2='朋友多了路真的好走吗'
select substring(@Lctext2,number,1) as value
from master..spt