mysql stored function parameter - sql

I have just started to create a stored function this is my first time so I am having a few problems. Currently I call the function using SELECT test(); (test is the function name for now). I want to send a number to the function (username ID) and have the username returned.
I have this working by using SELECT test(1); 1 is the ID of a user in the table. This seems to work as the username is returned, but if I type in any number the same username is returned also.
BEGIN
DECLARE new_username VARCHAR(90);
SELECT `username` INTO new_username FROM `users` WHERE `ID` = ID;
return new_username;
END
I have set the paramter as ID int .
Am I right in thinking that the keyword INTO will put the value of the username into the variable new_username ? If I run it without the INTO I get the error:
Not allowed to return a result set from a function
Have I made any obvious mistakes in this, I hope I havent done it totally wrong. Thanks for any advice :).
Edit : I just added a few more rows into my table , I now get the error:
Result consisted of more than one row
Full sql version:
CREATE DEFINER=`elliotts`#`%` FUNCTION `test`(ID int)
RETURNS varchar(32) CHARSET latin1
BEGIN
DECLARE new_username VARCHAR(32);
SELECT `username`
INTO new_username
FROM `users`
WHERE `ID` = ID;
return new_username;
END

Use:
DROP FUNCTION IF EXISTS `example`.`test` $$
CREATE FUNCTION `example`.`test` (param INT) RETURNS VARCHAR(32)
BEGIN
DECLARE new_username VARCHAR(32);
SELECT `username`
INTO new_username
FROM `users`
WHERE `ID` = param;
RETURN COALESCE(new_username, 'Username not found');
END $$
Mind that the VARCHAR length of the RETURN value matches the variable, which should match the column length you want to return.

Related

SQL Server 2016 - Variable showing NULL

We have a scalar function in our application as below
CREATE function dbo.SCMGetEnvProfileValueFn
(#HierarchyCode varchar(255), -- Usually the subsystem code
#Code varchar(50), -- The Code to find
#Default varchar(255) -- If not found, return this default
)
RETURNS varchar(255)
AS
BEGIN
DECLARE #Value as varchar(255)
SELECT #Value = (SELECT TOP(1) Value FROM HVCEnvProfile
WHERE HierarchyCode = #HierarchyCode
AND Code = #Code)
RETURN ISNULL (#Value, #Default)
END
We converted this function to Table function
CREATE FUNCTION SCMGetEnvProfileValueTblFn
(#HierarchyCode varchar(255), -- Usually the subsystem code
#Code varchar(50), -- The Code to find
#Default varchar(255) -- If not found, return this default
)
RETURNS TABLE
AS
RETURN
(SELECT TOP(1) ISNULL (Value, #Default) AS value
FROM HVCEnvProfile
WHERE HierarchyCode = #HierarchyCode AND Code = #Code)
Below 2 statements shows different output. We do not have a column in the table HVCEnvProfile for this entry. Why the variable #Value is showing NULL when there is no row in the table.
SELECT value
FROM dbo.SCMGetEnvProfileValueTblFn('Registration', 'AdmitDtmEffectsLocationHistory', 'TRUE')
SELECT dbo.SCMGetEnvProfileValueFn('Registration', 'AdmitDtmEffectsLocationHistory', 'TRUE')
If a query returns no rows, then no rows will be returned, wrapping an ISNULL won't change that. Example:
SELECT ISNULL(V.C,0)
FROM (VALUES(1),(2),(3),(4))V(C)
WHERE V.C = 5;
Notice this does not return 0, but nothing.
You need to wrap the entire query in an ISNULL.
CREATE FUNCTION SCMGetEnvProfileValueTblFn (#HierarchyCode varchar(255), -- Usually the subsystem code
#Code varchar(50), -- The Code to find
#Default varchar(255) -- If not found, return this default
)
RETURNS table
AS
RETURN
SELECT ISNULL((SELECT TOP (1) [Value]
FROM HVCEnvProfile
WHERE HierarchyCode = #HierarchyCode
AND Code = #Code
ORDER BY SomeColumn), #Default) AS [Value]; --Don' forgot to change the value of SomeColumn
Don't forget, as well, you need an ORDER BY when using a TOP unless you're "happy" with inconsistent results (which I doubt), so i have added one that you will need to amend.

Linked Table Valued Function Parameters (SQL Server)

I need to create a SQL Server TVF that takes a single param and then used that param to build the other required parameters. Is this even possible?
The error states incorrect syntax near 'LEFT'. Simple representation below.
CREATE FUNCTION TESTFUNCTION
(
-- Add the parameters for the function here
#PRM1 VARCHAR(2) = 'ABC',
#PRM2 VARCHAR(1) = LEFT(#PRM1,1)
)
RETURNS TABLE
AS
RETURN
(
-- Add the SELECT statement with parameter references here
SELECT #PRM2
)
GO
Thank You!
BEFORE EDIT MADE IN THE QUESTION :
You need only one parameters :
SELECT #PRM2 = LEFT(#PRM1, 1);
However, you need scaler function not table valued function :
CREATE FUNCTION TESTFUNCTION
(
-- Add the parameters for the function here
#PRM1 VARCHAR(2) = 'ABC'
)
RETURNS VARCHAR(255)
AS
BEGIN
DECLARE #PRM2 VARCHAR(255)
SET #PRM2 = LEFT(#PRM1, 1)
RETURNS (#PRM2)
END
Note : Your #PRM1 will accept only two characters which are AB. So, define appropriate length.

Throw a customized error when more chars than expected are passed in a SQL function attribute

I have created a SQL Server function like that:
function [schema].[function_name]
(#ids varchar(5))
but when I call it like with an #ids attribute with more chars than expected e.g.,
select *
from db.schema.function_name('ABCDEFGHIJKLMNOPQRST')
I get no error. How can I throw a customized error in that case? Such as "you passed more chars than expected".
This should be simple
create function dbo.test
(
#id varchar(30)
)
returns varchar(30)
as
begin
if len(#id)>10
begin
return 'Length exceeded'
end
return 1
end
Testing :
select dbo.test(replicate('a',14))
returns
Length exceeded

function in sql

I made a relation of criminal cases in a police station.
CREATE TABLE C_CASE
(
Case_ID int,
Case_Details varchar(255),
Case_Status varchar(255),
Section_Of_Law varchar(255)
);
INSERT INTO C_CASE
VALUES(333,'Hit and Run','Pending','304(A)');
INSERT INTO C_CASE
VALUES(444,'Robbery','Closed','392');
INSERT INTO C_CASE
VALUES(555,'Extortion','Pending','384');
INSERT INTO C_CASE
VALUES(222,'Murder','Closed','302');
I created a function which will return the number of Cases which are pending.
but I get an error. The function is :
create function NumOfCases(#statustype varchar(255)) returns varchar(255)
as
begin
return
(
select count(Case_Status) from C_CASE where Case_Status=#statustype
)
end
QUERY:
select from dbo.NumOfCases('Pending');
I keep getting the error:
Msg 156, Level 15, State 1, Line 21
Incorrect syntax near the keyword 'from'.
Where am I going wrong?
First, you need to change the return type of your function from varchar to integer using RETURNS int as you are trying to return a count.
The way you should call the function from sql is like this
select db.NumOfCases('Pending') as YourCount
You have several issues here. You did not name your column in your function. Then in your query you didn't specify anything to select. Since your query is a scalar function you don't use FROM. I would suggest however that you don't want a scalar function at all . The performance of them is horrible. A inline table valued function would be far better. Something like this.
create function NumOfCases
(
#statustype varchar(255)
) returns table
as
return
select count(Case_Status) as StatusCount
from C_CASE
where Case_Status = #statustype
Then to use this you could do something like this.
Select StatusCount
from NumOfCases('Pending')
You might also consider normalizing the status values. I would suggest using a Status table to hold the text values of your statuses. Then you have just the StatusID in your Case table.
Since it is a count of something use Integer for your return type.
create function NumOfCases(#statustype varchar(255))
returns INT
as
begin
Declare #RtnValue INT;
select #RtnValue = count(Case_Status) from C_CASE where Case_Status=#statustype
return #RtnValue
end

stored procedure with isnull(expression, replacement) return nothing

I have a stored procedure that accepts parameter and return tuple with matching values. If no parameter is passed, then return every tuple in the table
create procedure getScore
(
#clinicCode varchar = null,
)
as
begin
select * from myTable
where ClinicCode = isnull(#clinicCode, ClinicCode)
end
so I executte it
exec getScore
exec getScore 'PSH'
both of them return no tuple.
I did try select * from myTable, and they returns all tuples. Not sure why the statement from ... isnull(expression, replacement) get messed up
You need to change the declaration of
#clinicCode varchar = null,
to the actual size you require.
So something like
#clinicCode varchar(50) = null,
The reason for this is that
#clinicCode varchar
is the same as
#clinicCode varchar(1)
Which then casts your field isnull(#clinicCode, ClinicCode) to only the first letter of ClinicCode
Have a look at this example
SQL Fiddle DEMO