Scalar valued function not found - sql

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

Related

How to print Alphabets using UDF Scalar function?

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]()

Calling scalar function through Exec

I have created a scalar function
CREATE FUNCTION dbo.Dumm()
returns INT
AS
BEGIN
DECLARE #a INT
SELECT #a = 1
RETURN #a
END
Now I am calling the scalar function through Exec not through select
EXEC dbo.Dumm
It did not return 1. It just says
Command(s) completed successfully.
Whats happening internally. Is there any meaning for it ?
Try this:
DECLARE #ret int;
EXEC #ret = dbo.Dumm
and then show the result querying your variable #ret as follow:
SELECT #ret
Tell me if it's OK

user defined function call vs calling UDF in a Store procedure

I have a user defined function that is called inside a stored procedure. All that stored procedure does is return the value that is obtained from the UDF scalar function.
However,
Select * UDF_FunctionName(param1,param2)
udf call is here-
SELECT dbo.udfFunction('1234',10) as result
and
Exec StoreProcName(param1,param2)
are returning different results.
StoreProcName calls the `UDF_FunctionName(param1,param2)
sproc code is here-
BEGIN
SET NOCOUNT ON;
Return SELECT [DbName].[dbo].[udfFunction](#param1, #param2)
END
What could be the reason for different results?.
You are trying to use RETURN and SELECT together:
Return SELECT [DbName].[dbo].[udfFunction](#param1, #param2)
You cannot do that, you either want to return the result, or select it. Depending on which you choose, retrieving the value will differ.
If you do this:
SELECT [DbName].[dbo].[udfFunction](#param1, #param2)
Then the resultset will have a single row and column containing your value. Access this exactly as you would any other resultset.
If you do this:
RETURN [DbName].[dbo].[udfFunction](#param1, #param2)
Your stored procedure will have a return value which is the result of your function call. Access this by defining a scalar variable and assigning it to the result of the SP call - assuming the result is INT that might look like
DECLARE #result INT
EXEC #Result = StoredProcName(#param1, #param2)
You should not use RETURN in this way in a stored procedure. If you want to return a scalar value to the calling code use an OUTPUT parameter. RETURN is generally used for status codes.
You might have something like
-- SAMPLE UDF
CREATE FUNCTION dbo.YourUDF (#Username VARCHAR(30), #EntityID INT)
RETURNS INT
AS
BEGIN
RETURN #EntityID;
END
GO
-- SAMPLE PROCEDURE
CREATE PROCEDURE dbo.YourProc #Username VARCHAR(30), #EntityID INT, #Output INT OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SET #Output = dbo.YourUDF(#Username, #EntityID);
IF #Output IS NULL -- AN ERROR
BEGIN
RETURN 1; -- RETURN A STATUS OF -1 TO INDICATE ERROR
END
END
Then you could call this as:
DECLARE #Output INT, #ReturnValue INT;
EXECUTE #ReturnValue = dbo.YourProc
#Username = '1234',
#EntityID = 1,
#Output = #Output OUTPUT;
SELECT ValueFromUDF = #Output,
ReturnValue = #ReturnValue;
This returns:
ValueFromUDF ReturnValue
------------------------------
1 0
If we pass NULL as #EntityID, to trigger the artificial error, then we get a return status of -1:
DECLARE #Output INT, #ReturnValue INT;
EXECUTE #ReturnValue = dbo.YourProc
#Username = '1234',
#EntityID = NULL,
#Output = #Output OUTPUT;
SELECT ValueFromUDF = #Output,
ReturnValue = #ReturnValue;
ValueFromUDF ReturnValue
------------------------------
NULL 1

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
?

creating function using newID()

I keep getting this error: Any Ideas?
Invalid use of side-effecting or time-dependent operator in 'newid' within a function.
I am working with MS-SQL Server 2005. Here is the T-SQL statement:
Create Function [dbo].[GetNewNumber]( )
RETURNS int
AS
BEGIN
Declare #code int
set #code = (SELECT CAST(CAST(newid() AS binary(3)) AS int) )
RETURN (#code)
END
You can't use NEWID() within a function.
A usual workaround (in my experience, it's more been the need for GETDATE()) is to have to pass it in:
Create Function [dbo].[GetNewNumber](#newid UNIQUEIDENTIFIER )
RETURNS int
AS
BEGIN
Declare #code int
set #code = (SELECT CAST(CAST(#newid AS binary(3)) AS int) )
RETURN (#code)
END
And call it like:
SELECT dbo.GetNewNumber(NEWID())
The function will not let you use the NewID, but this can be worked around.
Create View vwGetNewNumber
as
Select Cast(Cast(newid() AS binary(3)) AS int) as NextID
Create Function [dbo].[GetNewNumber] ( ) RETURNS int
AS
BEGIN
Declare #code int
Select top 1 #code=NextID from vwGetNewNumber
RETURN (#code)
END
Then you can use select dbo.[GetNewNumber]() as planned.
Does this have to be done with a function call? Whenever I needs this functionality, I just use:
checksum(newid())
This will generate negative numbers -- if they must be positive, you could use
abs(checksum(newid()))