Take the 2-minute tour ×
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

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
share|improve this question

1 Answer 1

up vote 3 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.