3

这就是我所做的。

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

我不断收到错误:

消息 156,级别 15,状态 1,过程 INITCAP,第 97 行
关键字“exec”附近的语法不正确。
消息 156,级别 15,状态 1,过程 INITCAP,第 100 行
关键字“exec”附近的语法不正确。

我该怎么办?我希望该过程INITCAP像在 Oracle 中一样工作:返回一个名称,如:“Steve”、“Miller”

4

3 回答 3

5

解决方案#1(我不会使用此解决方案)

您可以这样使用 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);
于 2013-10-12T21:59:59.863 回答
1

你真的需要一个存储的过程吗???我会做这样的事情,我认为 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;

您可以在SELECT语句中调用此函数,让 proc 执行相同的工作不会给您这种灵活性

更新

UPDATE Employee 
SET firstname = dbo.udf_SomeFunction (firstname)
, lastname = dbo.udf_SomeFunction (lastname)
WHERE empID = 7934
于 2013-10-12T21:58:06.710 回答
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
于 2013-10-12T22:02:17.403 回答