2

Is there a way to name the column in a table valued function depending on the input of the user to the function?

Suppose there is some function:

foo(1,2,3)

So it takes three integer inputs. Now suppose I would like to return the column names in the table like: '1 some text', '2 some text', '3 some text'.

Is this possible?

4
  • Have you tried appending the function arguments as an alias names in the result set!? Commented Jul 7, 2016 at 9:51
  • nope. I didn't think about it, let me try that. Commented Jul 7, 2016 at 9:59
  • what is the syntax for that? this does not seem to work: INSERT INTO \@Table SELECT \@parameter1 as (\@parameter1 + 'some text') Commented Jul 7, 2016 at 10:01
  • In order to create the column names for the result set, need to use EXEC inside the function which the UDFs doesn't support. However this can be achieved using the procedures. I have mock-up for a procedural retrieval. Let me know if that helps, Commented Jul 7, 2016 at 10:54

3 Answers 3

2

If you need an SP approach, you can extend it using,

CREATE PROCEDURE Foo(@Input1 INT, @Input2 INT, @Input3 INT) AS 
DECLARE @X VARCHAR(100) 

SET @X = 'Select ' + 'Id ' + ' AS [' + convert(varchar(10), @Input1) + 'SomeText]' + 
', FirstName ' + ' AS [' + convert(varchar(10), @Input2) + 'SomeText' + ']' + 
', LastName ' + ' AS [' + convert(varchar(10), @Input3) + 'SomeText' + ']' +
         ' From Emp' 

EXEC (@X) 

GO 

Foo 1, 2, 3
Sign up to request clarification or add additional context in comments.

Comments

2

No. Table-Valued Functions -- Multi-statement TVF, Inline TVF, or SQLCLR TVF -- need to return a consistent / deterministic result set. This is similar to Scalar UDFs (T-SQL and SQLCLR) needing to always return the same datatype.

In fact, the result set to be returned by any TVF, regardless of the type of TVF, is defined in the system meta-data when the TVF is created, and cannot be changed at run-time. You can see the definitions using the following query:

SELECT so.type_desc AS [ObjectType], so.[name] AS [ObjectName], sc.*
FROM sys.columns sc
INNER JOIN sys.objects so
        ON so.[object_id] = sc.[object_id]
WHERE so.type_desc NOT IN ('SYSTEM_TABLE', 'USER_TABLE', 'INTERNAL_TABLE',
                           'VIEW', 'TYPE_TABLE')
ORDER BY so.[type_desc], so.[name], sc.column_id;

For ObjectType, you can get back entries having the following values:

  • CLR_TABLE_VALUED_FUNCTION
  • SQL_INLINE_TABLE_VALUED_FUNCTION
  • SQL_TABLE_VALUED_FUNCTION

Comments

1

This can be achieved by using dynamic SQL, but remember you cannot have it inside a function. Try creating a SP..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.