How to print Alphabets using UDF Scalar function? - sql

I am trying to print Alphabets by creating UDF scalar function.
Here is my code:
create function [dbo].[fnalphabets]()
returns varchar
as begin
declare #num int=65
while(#num<=90)
begin
set #num=#num+1
end
return char(#num)
end
when I am calling this function using
select dbo.fnalphabets()
It doesn't returns expected result. could anyone let me know what is wrong with my code?

No need of Loop or Function anything. Just take Spt_Values table from master database for numbers and do cast them to Char
SELECT CHAR(number)
FROM master.dbo.spt_values
WHERE type = 'p'
AND NUMBER BETWEEN 65
AND 90
ORDER BY NUMBER
Edit:
From Comments : UDF for the above code
Go
ALTER FUNCTION [dbo].[fnalphabets]()
RETURNS VARCHAR(MAX)
AS BEGIN
DECLARE #Alphabates VARCHAR(130)='';
SELECT #Alphabates = #Alphabates +CHAR(number) +'
'
FROM master.dbo.spt_values
WHERE type = 'p'
AND NUMBER BETWEEN 65
AND 90
ORDER BY NUMBER
RETURN #Alphabates
END

Try this: I changed its return varchar size here and declare variable to Store the alphabet string. and storing char values in it in while loop. as below and return the same alphabet string.
CREATE FUNCTION [dbo].[fnalphabets]()
RETURNS VARCHAR(MAX)
AS BEGIN
DECLARE #num INT=65
DECLARE #Alphabates VARCHAR(100)=''
WHILE(#num<=90)
BEGIN
SET #Alphabates=#Alphabates+char(#num)
SET #num=#num+1
END
RETURN #Alphabates
END

TRY THIS: you can use Table Valued Functions as below, it will give you each A-Z in separate rows:
CREATE FUNCTION [dbo].[fnalphabets]()
RETURNS #list TABLE (alphabet VARCHAR(10))
BEGIN
DECLARE #num INT=65
WHILE(#num<=90)
BEGIN
INSERT INTO #list SELECT CHAR(#num)
SET #num=#num+1
END
RETURN
END
SELECT * FROM [dbo].[fnalphabets]()

Related

User Defined Function to determine whether string contains a substring

I have this code which is currently returning 0 regardless if the string contains the substring or not. It should return 1 if the substring is found.
CREATE FUNCTION dbo.checkLetters (#MESSAGE VARCHAR)
RETURNS INTEGER
WITH RETURNS NULL ON NULL INPUT
AS
BEGIN
DECLARE #value INTEGER;
IF #MESSAGE LIKE '%findMe%'
SET #value = 1
ELSE
SET #value = 0
RETURN #value
END;
I also tried using charindex in my IF statement to no avail. Am I missing something simple here?
Testing like so:
SELECT dbo.checkletters('dLHLd');
use (#MESSAGE VARCHAR(max)) as a input parameter. or instead of max specify the length, currently in your function it is only 1. That is the issue.
Modify your function as given below:
ALTER FUNCTION dbo.checkLetters (#MESSAGE VARCHAR(max))
RETURNS INTEGER
WITH RETURNS NULL ON NULL INPUT
AS
BEGIN
DECLARE #value INTEGER;
DECLARE #ExpressionToFind VARCHAR(50)
SET #ExpressionToFind = 'findme'
IF #MESSAGE LIKE '%' + #ExpressionToFind + '%'
SET #value = 1
ELSE
SET #value = 0
RETURN #value
END;
The problem was in your input parameter.
Your function could be rewritten as:
CREATE FUNCTION dbo.checkLetters (#MESSAGE VARCHAR(MAX))
RETURNS BIT
WITH RETURNS NULL ON NULL INPUT
AS
BEGIN
RETURN CAST(CHARINDEX('findMe', #MESSAGE) AS BIT);
END
CHARINDEX will find position of #MESSAGE in given string and if it's higher than 1, it will output 1 (bit operator).

Creating multiple UDFs in one batch - SQL Server

I'm asking this question for SQL Server 2008 R2
I'd like to know if there is a way to create multiple functions in a single batch statement.
I've made the following code as an example; suppose I want to take a character string and rearrange its letters in alphabetical order. So, 'Hello' would become 'eHllo'
CREATE FUNCTION char_split (#string varchar(max))
RETURNS #characters TABLE
(
chars varchar(2)
)
AS
BEGIN
DECLARE #length int,
#K int
SET #length = len(#string)
SET #K = 1
WHILE #K < #length+1
BEGIN
INSERT INTO #characters
SELECT SUBSTRING(#string,#K,1)
SET #K = #K+1
END
RETURN
END
CREATE FUNCTION rearrange (#string varchar(max))
RETURNS varchar(max)
AS
BEGIN
DECLARE #SplitData TABLE (
chars varchar(2)
)
INSERT INTO #SplitData SELECT * FROM char_split(#string)
DECLARE #Output varchar(max)
SELECT #Output = coalesce(#Output,' ') + cast(chars as varchar(10))
from #SplitData
order by chars asc
RETURN #Output
END
declare #string varchar(max)
set #string = 'Hello'
select dbo.rearrange(#string)
When I try running this code, I get this error:
'CREATE FUNCTION' must be the first statement in a query batch.
I tried enclosing each function in a BEGIN END block, but no luck. Any advice?
Just use a GO statement between the definition of the UDFs
Not doable. SImple like that.
YOu can make it is one statement using a GO between them.
But as the GO is a batch delimiter.... this means you send multiple batches, which is explicitly NOT Wanted in your question.
So, no - it is not possible to do that in one batch as the error clearly indicates.

Scalar valued function not found

I have made the following scalar valued function
CREATE FUNCTION [dbo].[CountCustomers]
(
#Name varchar
)
RETURNS int
AS
BEGIN
DECLARE #Result int
SET #Result = 1
RETURN #Result
END
But when I am calling it as
SELECT dbo.CountCustomers
I am not able to do it.
You defined a parameter for your function (#Name), so call the function with a value for that parameter:
SELECT dbo.CountCustomers('foo')
You need to pass a value into your function such as this:
SELECT dbo.CountCustomers('name')
The reason is you have #Name varchar as a parameter.
You can also call it like this:
DECLARE #Count INT
SET #Count = dbo.CountCustomers('name')
SELECT #Count
You need to add parentheses to call the function, and then add in one parameter in order for it to work.
SELECT dbo.CountCustomers('hello world')

If a value contains a certain character then do this or else do this

I am trying to write a function which processes a column value and returns the value with everything before the '#' symbol.
I have managed to do this so far by using the following code:
Create Function fnStaffCodeConvert (#staffcode varchar(10))
Returns varchar(4)
AS
BEGIN
DECLARE #staffinitals varchar(4)
SET #staffinitals = (SELECT substring(#staffcode,0, CHARINDEX('#',#staffcode)))
Return #staffinitials
END
Example result from function - Parameter in = ABC#123, Returns = ABC.
This works but then exclusively returns every result where the column contained an # value and the remaining results without the # are omitted. I.e. ABC#123 returns ABC but XYZ does not return anything.
How can I amend the code to give me both sets of values? I imagine I would have to put an 'IF' statement in there but I am unsure how to write it to get the results I want.
Many thanks in advance :)
Mike
You are almost there:
ALTER FUNCTION fnStaffCodeConvert (#staffcode varchar(10))
RETURNS VARCHAR(4)
AS
BEGIN
DECLARE #staffinitals AS VARCHAR(4)
if CHARINDEX('#',#staffcode) <> 0
SET #staffinitals = (SELECT substring(#staffcode,0, CHARINDEX('#',#staffcode)))
Else
SET #staffinitals = #staffcode
RETURN #staffinitals
END
You can do what you want with a case:
Create Function fnStaffCodeConvert (#staffcode varchar(10))
Returns varchar(4);
AS
BEGIN
DECLARE #staffinitals varchar(4);
SET #staffinitals = (SELECT (case when #staffcode like '%#%'
then substring(#staffcode,0, CHARINDEX('#',#staffcode)
else #staffcode
end));
Return #staffinitials;
END
But wait, you can simplify this further:
Create Function fnStaffCodeConvert (#staffcode varchar(10))
Returns varchar(4)
AS
BEGIN
DECLARE #staffinitals varchar(4)
SELECT #staffinitials = (case when #staffcode like '%#%'
then substring(#staffcode,0, CHARINDEX('#',#staffcode)
else #staffcode
end);
Return #staffinitials;
END;

Unable to retrieve value returned from mysql function

Since a week am working with MYSQL , got to execute the Stored Procedure as well as Views but Facing some problem retrieving the values returned from a function.
Here's the Function:
CREATE DEFINER=`root`#`localhost` FUNCTION `GetProductIdsStringByEnquiryId`
(
InEnquiryId int
) RETURNS varchar(4000) CHARSET utf8
BEGIN
DECLARE InProductIds varchar(4000);
DECLARE ProductId varchar(50);
DECLARE x,y,z INT;
DECLARE sp1_cursor CURSOR FOR SELECT ProductId FROM enquiryproductid where
EnquiryId=InEnquiryId;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET z = 1;
SET InProductIds='';
OPEN sp1_cursor;
REPEAT
FETCH sp1_cursor INTO ProductId;
SETInProductIds=concat(InProductIds,ProductId,',');
UNTIL (z=1)
END REPEAT;
CLOSE sp1_cursor;
RETURN InProductIds ;
END
I was initially working with SQL SERVER 2005, and the function which I have written in their I tried converting it as above in MYSQL,
Here's the SQL Function Code:
CREATE function [dbo].[GetBranchIdsStringByEmployeeId]
(
#EmployeeId as integer
)
returns nvarchar(4000)
as
begin
declare #BranchIds as nvarchar(4000)
set #BranchIds=''
if exists(select 1 from dbo.BranchEmployees where EmployeeId=#EmployeeId)
begin
select #BranchIds=#BranchIds+cast(BranchId as nvarchar(50))
+',' from dbo.BranchEmployees where EmployeeId=#EmployeeId
order by BranchId
end
return #BranchIds
end
Can anybody Please Let me know if the Function What I have written in MYSQL is in ProperManner or not? Please do help me out.
Thank You.
Not read fully through it, but few comments
Variable assignment in mysql uses := (in set #variable it is ok to use =, in select #variable:=#variable+1)
Are you trying to
SELECT group_concat(BranchId)
FROM dbo.BranchEmployees
WHERE EmployeeId = #EmployeeId
?