Function should have input parameters? - sql-server

Is it mandatory to pass input parameters for all the user defined functions?
We know, Stored procedure has both input and output parameters.
Function has only input parameters.
We can write a stored procedure without using these parameters too..
Is it possible to write the user defined function without input parameter?

Yes you can definitely write User defined function without parameter.
One more thing I want to clarify that function may have input parameter and it has return value. Return value would be scalar or table depend on type of function you are creation.

Why ask if it is possible when you can just type a few lines and see that it is possible ;-)
CREATE FUNCTION dbo.NoParamsUDF()
RETURNS NVARCHAR(50)
AS
BEGIN
RETURN N'It worked!';
END;
GO
CREATE FUNCTION dbo.NoParamsTVF()
RETURNS TABLE
AS RETURN
SELECT dbo.NoParamsUDF() AS [DidItWork?];
GO
SELECT * FROM dbo.NoParamsTVF();
Returns:
DidItWork?
-------------
It worked!

CREATE FUNCTION dbo.NoParamsUDF()
RETURNS VARCHAR(50)
AS
BEGIN
RETURN N'It worked!';
END;
GO
CREATE FUNCTION dbo.NoParamsTVF()
RETURNS TABLE
AS RETURN
SELECT dbo.NoParamsUDF() AS [DidItWork?];
GO
SELECT * FROM dbo.NoParamsTVF();

Related

Inline User Defined Function for a view having parameters

I am using an openquery to get my data. Because of the length of my query which exceeds 8000 characters, I am using this approach :
DECLARE #myStatement VARCHAR(MAX)
SET #myStatement 'SELECT * FROM Employee...'
EXECUTE (#myStatement) AT [MyLinkedServer]
Knowing that it is not possible to use variables in a view, I am trying to use a User Defined function that returns a table like below :
CREATE FUNCTION dbo.EmployeeDetailsForHR
(#myStatement VARCHAR(MAX))
RETURNS TABLE
AS RETURN(EXECUTE (#myStatement) AT [MyLinkedServer]);
SELECT *
FROM dbo.EmployeeDetailsForHR('SELECT * FROM Employee...');
But my CREATE FUNCTION isn't correct. What is the correct syntax in my case?

New optional parameter in SQL Server database function [duplicate]

This question already has answers here:
Alter a SQL server function to accept new optional parameter
(3 answers)
Closed 4 years ago.
I have a stored procedure that looks like this:
CREATE FUNCTION [my_schema].[isEligible]
(#product NUMERIC(8))
RETURNS INT
AS
BEGIN
DECLARE #result INT;
/* do eligibility checking, setting #result */
RETURN #result;
END;
This is referenced in several existing queries similar to this:
SELECT *
FROM person
WHERE my_schema.isEligible(?) > -1 -- negative numbers are eligibility error codes
Where ? is the parameter for a given product id.
In one of the several queries that call the function, I need to pass in a new additional parameter, #exception. I want to have the function behave by default like it did before, and only change behavior for the one call that will be passing in a value for #exception, so I have added the new parameter like so:
CREATE FUNCTION [my_schema].[isEligible]
(#product NUMERIC(8),
#exception CHAR(1) = 'N')
RETURNS INT
AS
BEGIN
DECLARE #result INT;
/*
do eligibility checking (conditionally accounting for
#exception being 'Y'), and setting #result
*/
RETURN #result;
END;
But when I deploy the new version of the function and run a query which only passes in #product I'm getting An insufficient number of arguments were supplied for the procedure or function [my_schema].[isEligible]. I thought that adding = 'N' would provide a default value and avoid this issue.
I read here that sometimes this generic sounding error is actually hiding other errors which aren't allowed to bubble up, but I don't know if that's the case, since it's talking about procedures and this is a function. Not sure if there's a difference or if functions don't support optional arguments like procedures.
I'd love to not have to pass in NULL for the new parameter if possible, which would simplify the rollout of the updated version of the function. Is there a way to do call this function both like isEligible(?) and isEligible(?, ?) or do I need the first one to be isEligible(?, NULL) for it to work?
You could call your function as:
SELECT *
FROM person
WHERE my_schema.isEligible(?, default) > -1
and:
SELECT *
FROM person
WHERE my_schema.isEligible(?, value) > -1

Postgres function with jsonb parameters

I have seen a similar post here but my situation is slightly different from anything I've found so far. I am trying to call a postgres function with parameters that I can leverage in the function logic as they pertain to the jsonb query. Here is an example of the query I'm trying to recreate with parameters.
SELECT *
from edit_data
where ( "json_field"#>'{Attributes}' )::jsonb #>
'{"issue_description":"**my description**",
"reporter_email":"**user#generic.com**"}'::jsonb
I can run this query just fine in PGAdmin but all my attempts thus far to run this inside a function with parameters for "my description" and "user#generic.com" values have failed. Here is a simple example of the function I'm trying to create:
CREATE OR REPLACE FUNCTION get_Features(
p1 character varying,
p2 character varying)
RETURNS SETOF edit_metadata AS
$BODY$
SELECT * from edit_metadata where ("geo_json"#>'{Attributes}' )::jsonb #> '{"issue_description":**$p1**, "reporter_email":**$p2**}'::jsonb;
$BODY$
LANGUAGE sql VOLATILE
COST 100
ROWS 1000;
I know that the syntax is incorrect and I've been struggling with this for a day or two. Can anyone help me understand how to best deal with these double quotes around the value and leverage a parameter here?
TIA
You could use function json_build_object:
select json_build_object(
'issue_description', '**my description**',
'reporter_email', '**user#generic.com**');
And you get:
json_build_object
-----------------------------------------------------------------------------------------
{"issue_description" : "**my description**", "reporter_email" : "**user#generic.com**"}
(1 row)
That way there's no way you will input invalid syntax (no hassle with quoting strings) and you can swap the values with parameters.

PostgreSQL Declared Variable in Function

I work with Potgresql and I have written function
CREATE OR REPLACE FUNCTION staging.shape_commit(layer_id integer)
RETURNS integer AS
$BODY$
declare
layer_name text;
begin
layer_name:=(select shape.layer_name from staging.shape where shape.id=layer_id);
delete from layer_name;
return layer_name;
end;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION staging.shape_commit(integer)
OWNER TO test;
layer_name is variable and really it is table name .but script ignore it as variable and uses as string
Cam anybody help me?
Your question isn't quite clear, but I suspect that you actually want to convert the text to a table name. For this, you want dynamic SQL. Instead of:
delete from layer_name;
Try something more like:
execute $x$delete from $x$ || layer_name::regclass;
http://www.postgresql.org/docs/current/static/plpgsql-statements.html

From Visual Studio (C#) - How to indicate a DEFAULT value for a function while calling a sql server function

I have a sql server function that I would like to call from Visual C#. I want to use the DEFAULT value for one of the parameters. What value should I pass from Visual C# to accomplish this?
Thanks,
rkg
Assuming you mean something like this:
#MySampleSqlParam VarChar(50) = NULL
Because it's an optional parameter (it has a default supplied), all you need to do is simply not include that parameter when you call the procedure. So just omit adding the SqlParameter to the SqlCommand.Parameters collection.
Try this :
cmd.Parameters.Add("#YourParameter", SqlDbTypes.YourType).Value = DBNull.Value;
I would pass a nullable type into the function. Just don't pass the parameter if it's null:
public void saveSomething(int? somethingID, string somethingName)
{
if (somethingID.HasValue)
{
//add the parameter
}
}
And use a default value in the sproc:
#SomethingID INT = NULL
Obviously, you'll also need to add logic to ignore the condition when the parameter is null.
Seems like you are looking for optional parameter in SQL. just Google for optional parameter in SQL.
You can create a function with a preset value for the parameter as:
CREATE FUNCTION dbo.fnMyFunction
(
#Param1 INT,
#Param2 INT = 2 --Default Values is Set no need to get it from parameter
)
RETURNS ..

Resources