Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server : return string procedure INITCAP

This is what I've done.

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

I keep getting the errors:

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'.

What shall I do? I want the procedure INITCAP to work as it does in Oracle: to return a name like: "Steve", "Miller"

like image 348
Kilise Avatar asked Dec 21 '25 09:12

Kilise


2 Answers

Solution #1 (I wouln't use this solution)

You could use OUTPUT parameters thus:

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

Solution #2: Instead, I would choose to create an inline function thus:

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

Usage:

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

Solution #3: Another option could be a scalar function with schemabinding option (for performance reasons):

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;

Usage:

UPDATE Employee
SET firstname = dbo.Capitalize2(firstname);
like image 93
Bogdan Sahlean Avatar answered Dec 22 '25 23:12

Bogdan Sahlean


Do you really need a stored Proc for this ??? I would do something like this a UDF would do the job just fine i think....

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;

You can call this function in your SELECT statement , Having a proc doing the same job doesnt give you this flexibility

UPDATE

UPDATE Employee 
SET firstname = dbo.udf_SomeFunction (firstname)
, lastname = dbo.udf_SomeFunction (lastname)
WHERE empID = 7934
like image 21
M.Ali Avatar answered Dec 22 '25 23:12

M.Ali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!