Create a Function in sql server without specifying return_data_type
-
22-10-2019 - |
Question
I am trying to create a Scalar-valued function in SQL server, without specifying the return_data_type
i want to be able to return any datatype based on a parameter sent by the function caller
e.g.
CREATE FUNCTION GenerateRandomData
(
@Datatype varchar(20)
)
RETURNS <Return any datatype specified by @Datatype parameter>
AS
BEGIN
-- Declare the return variable here
IF @Datatype in ('varchar','char','nchar','nvarchar','text','ntext')
Begin
RETURN 'String'
end
Else
IF @Datatype in ('int','bigint','smallint')
Begin
RETURN 100
end
Else
IF @Datatype in ('datetime','smalldatetime')
Begin
RETURN getdate()
end
END
Solution
You can't.
The return datatype must be specified in a function. It is not an optional part of the grammar. You can return sql_variant
though.
Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange