2013-10-12 59 views
2

這就是我所做的。SQL Server:返回字符串過程INITCAP

create proc INITCAP(@string varchar(30)) 
as 
begin 
    SET @string = UPPER(LEFT(@string,1)) + LOWER(RIGHT(@string, LEN(@string) -1)) 
end 

declare @lastname varchar 
set @lastname = exec INITCAP 'MILLER' 

declare @firstname varchar 
set @firstname = exec INITCAP 'StEvE' 

UPDATE Employee SET firstname = @firstname, lastname = @lastname WHERE empID = 7934 

我不斷收到錯誤:

Msg 156, Level 15, State 1, Procedure INITCAP, Line 97
Incorrect syntax near the keyword 'exec'.
Msg 156, Level 15, State 1, Procedure INITCAP, Line 100
Incorrect syntax near the keyword 'exec'.

我該怎麼辦?我想讓程序INITCAP像在Oracle中一樣工作:返回一個名稱,如:「Steve」,「Miller」

回答

4

溶液#1(I wouln't使用此解決方案)

你可以這樣使用OUTPUT參數:

create proc INITCAP(@string varchar(30) OUTPUT) 
as 
begin 
    SET @string = UPPER(LEFT(@string,1)) + LOWER(SUBSTRING(@string, 2, 8000)) 
end 
go 

declare @lastname varchar 
set @lastname = 'MILLER' 
exec INITCAP @lastname OUTPUT 

declare @firstname varchar 
set @firstname = 'StEvE' 
exec INITCAP @firstname OUTPUT 

解決方案#2:相反,我會選擇創建這樣一個內聯函數:

CREATE FUNCTION dbo.Capitalize1(@string varchar(30)) 
RETURNS TABLE 
AS 
RETURN 
SELECT UPPER(LEFT(@string,1)) + LOWER(SUBSTRING(@string, 2, 8000)) AS Result; 

用法:

UPDATE e 
SET firstname = cap.Result 
FROM Employee e 
CROSS APPLY dbo.Capitalize1(e.firstname) cap; 

解決方案#3:另一種選擇可能是一個標量函數with schemabinding選項(由於性能原因):

CREATE FUNCTION dbo.Capitalize2(@string varchar(30)) 
RETURNS VARCHAR(30) 
WITH SCHEMABINDING 
AS 
BEGIN 
    RETURN UPPER(LEFT(@string,1)) + LOWER(SUBSTRING(@string, 2, 8000)); 
END; 

用法:

UPDATE Employee 
SET firstname = dbo.Capitalize2(firstname); 
+0

解決方案#2應該給你最好的性能,特別是當你需要更新多個人時。 –

+1

是的,嘗試功能,但沒有得到它。現在,當你向我展示我當然會用它作爲一個功能!謝謝! – Kilise

+0

即時仍然收到錯誤:'INITCAP'不是一個公認的內置函數名稱。使用3解決方案(更改func的名稱到INITCAP) – Kilise

1

您真的需要存儲Proc嗎?我會做一些這樣的UDF會做的工作就好了,我認爲....

CREATE FUNCTION dbo.udf_SomeFunction (@String VARCHAR(30)) 
RETURNS VARCHAR(30) 
AS 
BEGIN 
    DECLARE @rtnString VARCHAR(30); 
    SET @rtnString = UPPER(LEFT(@string,1)) + LOWER(RIGHT(@string, LEN(@string) -1)) 
    RETURN(@rtnString); 
END; 

可以在調用這個函數您選擇聲明,有一個進程做同樣的工作犯規送給你靈活性

UPDATE

UPDATE Employee 
SET firstname = dbo.udf_SomeFunction (firstname) 
, lastname = dbo.udf_SomeFunction (lastname) 
WHERE empID = 7934 
+0

感謝您的幫助! – Kilise

+0

完全沒問題:) –

1

你應該用一個函數來實現你所需要的,並使用一個您需要設置變量的語法。請不要在功能創建和其他功能之間加入GO

create function INITCAP(@string varchar(30)) 
returns varchar(30) 
as 
begin 
    return UPPER(LEFT(@string,1)) + LOWER(RIGHT(@string, LEN(@string) -1)) 
end 

go 

declare @lastname varchar 
set @lastname = dbo.INITCAP('MILLER') 

declare @firstname varchar 
set @firstname = dbo.INITCAP('StEvE') 

UPDATE Employee SET firstname = @firstname, lastname = @lastname WHERE empID = 7934 
+0

感謝您的回答! – Kilise