Creating a user-defined table-valued function which should return select union all dynamic query.
I have table tbl_tablesinfo which contains table names tbl1, tbl2, tbl3, etc. in all around 3000 table names.
I don't want to create view but function which should return select * from all tables by doing union all.
My attempt:
CREATE FUNCTION udf_alldata()
RETURNS TABLE
AS
BEGIN
DECLARE @Var VARCHAR(MAX) = ''
SELECT
@Var = STUFF((SELECT ' SELECT * FROM [' + tbl.TableNames + '] UNION ALL'
FROM [TestDB].SYS.TABLES tb
INNER JOIN [TestDB].dbo.[tbl_tablesinfo] tbl ON tb.name = tbl.TableNames
FOR XML PATH('')), 1, 1, '');
SET @var = LEFT(@var, LEN(@var) - 10);
EXEC @var
RETURN
END
I'm getting an error:
Incorrect syntax near 'BEGIN'.
Reason for doing this is creating view with 3k tables is getting slow and taking around 30 min of time, so I am looking for an alternative by creating function.
returns tablewithout defining the table you are creating an inline table valued function which can only have areturn selectin it. It you want a regular table valued function you need to define the return table. Please consult the docs.