我有一个UDF,它会使每个作品的第一个字母成为一个大写的大写字母。我的问题是我想为此添加一些例外,我无法弄清楚如何做到这一点。
在我的数据库中,我有一列商业名称 - 例如 - mikes coffee shop,llc。
我的功能现在将返回 - Mikes Coffee Shop,Llc。我希望LLC处于上限,而其他商业名称是正确的。有关如何修改此功能的任何想法,以便像LLC或INC这样的东西全部上限?
CREATE FUNCTION [dbo].[InitCap] ( @InputString varchar(4000) )
RETURNS VARCHAR(4000)
AS
BEGIN
DECLARE @Index INT
DECLARE @Char CHAR(1)
DECLARE @PrevChar CHAR(1)
DECLARE @OutputString VARCHAR(255)
SET @OutputString = LOWER(@InputString)
SET @Index = 1
WHILE @Index <= LEN(@InputString)
BEGIN
SET @Char = SUBSTRING(@InputString, @Index, 1)
SET @PrevChar = CASE WHEN @Index = 1 THEN ' '
ELSE SUBSTRING(@InputString, @Index - 1, 1)
END
IF @PrevChar IN (' ', ';', ':', '!', '?', ',', '.', '_', '-', '/', '&', '''',
'(')
BEGIN
IF @PrevChar != '''' OR UPPER(@Char) != 'S'
SET @OutputString = STUFF(@OutputString, @Index, 1, UPPER(@Char))
END
SET @Index = @Index + 1
END
RETURN @OutputString
END
GO
答案 0 :(得分:1)
如果有兴趣,这里有一个可以在需要时扩展的功能。
示例强>
Declare @YourTable table (SomeCol varchar(100))
Insert Into @YourTable values
('old mcdonald'),
('dr. Langdon ,dds'),
('b&o railroad'),
('john-m-smith'),
('CARSON/jACOBS'),
('jAmes o''neil')
Select *
,ProperCase = [dbo].[svf-Str-Proper](SomeCol)
From @YourTable
<强>返回强>
SomeCol ProperCase
old mcdonald Old McDonald
dr. Langdon ,dds Dr. Langdon ,DDS
b&o railroad B&O Railroad
john-m-smith John-M-Smith
CARSON/jACOBS Carson/Jacobs
jAmes o'neil James O'Neil
UDF如果有兴趣
CREATE FUNCTION [dbo].[svf-Str-Proper] (@S varchar(50))
Returns varchar(max)
As
Begin
Set @S = ' '+Replace(Replace(Lower(@S),' ',' '),' ',' ')+' '
;with cte1 as (Select * From (Values(' '),('-'),('/'),('\'),('['),('{'),('('),('.'),(','),('&'),(' Mc'),(' O''')) A(P))
,cte2 as (Select * From (Values('A'),('B'),('C'),('D'),('E'),('F'),('G'),('H'),('I'),('J'),('K'),('L'),('M')
,('N'),('O'),('P'),('Q'),('R'),('S'),('T'),('U'),('V'),('W'),('X'),('Y'),('Z')
,('LLC'),('PhD'),('MD'),('DDS')
) A(S))
,cte3 as (Select F = Lower(A.P+B.S),T = A.P+B.S From cte1 A Cross Join cte2 B )
Select @S = replace(@S,F,T) From cte3
Return rtrim(ltrim(@S))
End
-- Syntax : Select [dbo].[svf-Str-Proper]('old mcdonald phd,dds llc b&o railroad')
答案 1 :(得分:0)
一种方法是使用REPLACE
来处理异常:
...
SET @OutputString = REPLACE(@outputString, 'Llc.', 'LLC.');
SET @OutputString = REPLACE(@OutputString, '...', '...');
RETURN @OutputString;
以分号结束每个语句是一个好习惯。