I Waint run code in SQL SERVER
ALTER FUNCTION return_table (@table nvarchar(250))
RETURNS TABLE
AS
RETURN
(
SELECT * FROM @table
)
none using PROCEDURE . THANK FOR HELP
I Waint run code in SQL SERVER
ALTER FUNCTION return_table (@table nvarchar(250))
RETURNS TABLE
AS
RETURN
(
SELECT * FROM @table
)
none using PROCEDURE . THANK FOR HELP
A function requires an explicit definition of the return value type, e.g. the columns being returned. The SQL statement you provided will not work in such a manner for the following reasons:
ALTER FUNCTION return_table (@table nvarchar(250)) -- You have declared a parameter of type table, this is not the right way of doing this
RETURNS TABLE -- you haven't defined the structure of the table being returned, this needs explicitly defining
AS
RETURN
(
SELECT * FROM @table -- using SELECT * is bad practice as the structure of the table may change and then conflict with the structure of the table being returned
)
The first part of the problem is declaring a parameter of type TABLE
; this question has good examples on how to get around doing this. Quick summary: you need to declare the table as a type before passing in the type as the parameter to your function:
CREATE TYPE MyTableParameterDefinition AS TABLE (
[ColumnName] NVARCHAR(250) NULL
)
This type can then be passed as a parameter to your function:
CREATE FUNCTION myFunctionName (
@TableVariable MyTableParameterDefinition READONLY
)...--INSERT CODE HERE--
I'm uncertain whether you can use a similar method for the return type and would suggest against this given the implication of the contract defined by the function. Better practice would be to define the structure of the table being returned and explicitly select the columns from the table:
ALTER FUNCTION return_table (
@table MyTableParameterDefinition
)
RETURNS TABLE
(
-- Explicitly define columns returned by the function
[ColumnName] NVARCHAR(250) NULL
)
AS
RETURN
(
SELECT
[ColumnName]
FROM
@table
)
The only way to make this work is truly horrible for both aesthetic and (probably) performance reasons. It also assumes that all tables that might be passed as parameters have the same structure:
ALTER FUNCTION return_table (@table sysname)
RETURNS TABLE
AS
RETURN
(
SELECT * FROM TableA where @table = 'TableA'
UNION ALL
SELECT * FROM TableB where @table = 'TableB'
UNION ALL
SELECT * FROM TableC where @table = 'TableC'
/* add more UNIONs and SELECTs for each table that you want to use */
)