|
create function dbo.capitalize (
-- capitalize the first character of every word,
-- sentence, or the whole string. put the rest to lowercase.
@string varchar (8000),
@capitalize_what varchar (8) = ’string’
-- string: capitalize the first letter of the string
-- sentence: capitalize the first letter of every sentence.
-- delimiters: ./!/?
-- word: capitalize the first letter of every word.
-- delimiters: any characters other than letters and digits.
)
returns varchar(8000)
as
begin
declare @position smallint,
@char char(1),
@first_char char (1),
@word_start smallint
set @capitalize_what = lower( @capitalize_what )
set @word_start = 0
if @capitalize_what in (‘word’, ‘sentence’)
begin
set @position = datalength( @string )
while @position >= 0 begin
set @char = case @position
when 0 then ’.’
else upper( substring(
@string, @position,
1 ) )
end
if @char between ’a’ and ’z’
or @char between ’0’ and ’9’ begin
set @word_start = @position
set @first_char = upper( @char )
end
else begin
if @capitalize_what = ’word’
or @char in ( ’.’, ’!’, ’?’ ) begin
if @word_start > 0
and @first_char between ’a’
and ’z’
set @string = stuff(
@string, @word_start,
1, @first_char )
set @word_start = 0
end
end
set @position = @position - 1
end
end
else begin -- capitalize the first character
set @position = 0
while @position < datalength( @string )
begin
set @position = @position + 1
set @char = upper( substring( @string,
@position, 1 ) )
if @char between ’a’ and ’z’
or @char between ’0’ and ’9’ begin
set @string = stuff( @string,
@position, 1, @char )
set @position = 9999
end
end
end
return( @string )
end
go
小结
sql server 2000 的 udf的应用是很广泛的,它会给编程人员带来极大的便利。您可以建立自己的’system’ udf,存在master数据库中,可以为任何数据库进行调用。
udf也有不足,我们知道系统函数可以任意调有,不管您使用大写、小写或者大小写混合。udf却不行,它是大小写敏感的。
在未来的版本中,我希望微软为udf增加默认值的功能,以后我们可以这样定义一个函数。
creat function dbo.test_default
( @parm int = 0 )
return int
as
begin
return ( @parm )
end
udf中诸如此类的小问题还有不少,希望udf的功能越来越强大,我们编程人员工作起来就会越来越轻松。
|