0

In my stored procedure, I have table variable with a lot of columns. Because I want to simplify the stored procedure I thought i could declare table variable in function like

CREATE FUNCTION [dbo].[ufn_DeclareMaterialTableVariable]
(
)
RETURNS @returntable TABLE
(
 [Id] [int] NULL,
 [Number] [int] NOT NULL,
 [Name] [nvarchar](255) NULL,
 ... dozens of columns
)
AS
BEGIN
 RETURN
END

but i realized i don't know, how to use it. My idea was something like

select * 
into @table
from [dbo].[ufn_DeclareMaterialTableVariable]

but this is not gonna work, unless i use temporary table.

The second idea is to declare table with custom data type.

declare @table TABLE as CustomTableType

but this is also not working. Any idea ?

asked Aug 20, 2019 at 9:24

1 Answer 1

2

You need to declare a table variable with the same shape as the TVF result, then use INSERT INTO not SELECT INTO, and remember to add brackets/parentheses to the end of the function name when invoking it, i.e. Foo() not just Foo:

DECLARE @Table TABLE (
 [Id] [int] NULL,
 [Number] [int] NOT NULL,
 [Name] [nvarchar](255) NULL,
 ... dozens of columns
);
// not best practice, but...
INSERT INTO @Table
SELECT *
FROM dbo.ufn_DeclareMaterialTableVariable();
// better - be explicit about the columns of interest
INSERT INTO @Table (
 [Id],
 [Number],
 [Name],
 ... dozens of columns
)
SELECT
 [Id],
 [Number],
 [Name],
 ... dozens of columns
FROM dbo.ufn_DeclareMaterialTableVariable();

If you've declared a table type, then the syntax for declaring a variable of that type is the following (note no TABLE keyword);

DECLARE @Table CustomTableType;

That said, annoyingly, you can't declare the result type of a TVF to be a table type - i.e. you always have to declare the returned columns again, explicitly - which partially negates the point of the custom type in the first place, in this situation.

answered Aug 20, 2019 at 9:54
1
  • Thank you, the second approach is exactly what i need :) Commented Aug 20, 2019 at 11:08

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.