How to create a function in SQL

/*Since I didn't write articles in eng for a while, I decide to make the explanation in eng. :P*/
/*The code is from SQL Server 2005 Bible and the footnote is my individual understanding on it.*/
--An interesting code to be the starting point for this section
--This function can realize the following example.
--Input ('haHa lolA') and it returns Haha Lola in the table.
--Below is the part how SQL creates a function;

Create FUNCTION pTitleCase (
			@StrIn varchar(1024))    --It's better if everything in eng. Or the string may make the function wrong.
RETURNS varchar(1024)
AS
 BEGIN
  DECLARE
	@StrOut varchar(1024),
	@CurrentPosition INT,
	@NextSpace INT,
	@CurrentWord varchar (1024),
	@StrLen INT,
	@LastWord BIT

Set @NextSpace = 1
Set @CurrentPosition = 1
Set @StrOut = ''
Set @StrLen = Len(@StrIn)
Set @LastWord = 0

While @LastWord = 0
  BEGIN
   Set @NextSpace = charindex(' ', @StrIn, @CurrentPosition+1)   --Find whether a SPACE in the input string for each one step. 
   IF  @NextSpace = 0 --No more space found!
	BEGIN
	 Set @NextSpace = @StrLen
	 Set @LastWord = 1            --Terminal of the loop
	END
   Set @CurrentWord = UPPER(substring(@StrIn, @CurrentPosition,1)) --If a SPACE found in the charindex line, it changes the alphebet following the SPACE uppercase.
   Set @CurrentWord = @CurrentWord + Lower(Substring(@StrIn,@CurrentPosition+1,@NextSpace-@CurrentPosition)) --After it puts all the alphebets following the UPPERCASE alphebet to lowercase...
   Set @StrOut = @StrOut +@CurrentWord --Appending...
   Set @CurrentPosition = @NextSpace + 1 
--2015-Jan-18 00:51 Not Sure why it is here??????????? Feel Like a bug.
--2015-Jan-19 09:45 This is not a bug, after reviewing the code, this one should read with the charindex line. The current position would jump to next space position plus one step.
 END
  Return @StrOut
END

And then when you

Select dbo.pTitleCase ('one TWO tHree') as [TitleCase]

It shows One Two Three under Column TitleCase.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

取啥都被占用

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值