0

Is there a way to send in a string into a T-SQL function and use that string as a "table"

For instance

CREATE FUNCTION [dbo].[TEST] ( @id int, **@table_name** nvarchar(50))
RETURNS @mytables TABLE
   (
    id     int,
    values nvarchar(50)
   )
AS
BEGIN
   INSERT @mytables
      SELECT id, values FROM **@table_name**
   RETURN
END  
3
  • No, you cannot do this directly - if you need to parametrize the table and/or column names, you must resort to using dynamic SQL - no other way to do it Commented Nov 27, 2013 at 10:23
  • I mean, I could use another function inside this function or whatever it doesn't matter. I just want to know if it can be done and how :) Commented Nov 27, 2013 at 10:25
  • Plus: a function in SQL Server cannot have any side effects on the database, e.g. you cannot insert, update or delete rows of data inside a function. See CREATE FUNCTION - section "Limitations and Restrictions": User-defined functions cannot be used to perform actions that modify the database state. Commented Nov 27, 2013 at 10:26

1 Answer 1

1

You can't use dynamic SQL in function, also can't insert, update or delete from any table in user defined function (Please check this link given by Marc), for your requirements, SP is best solution like this way :

CREATE PROCEDURE [dbo].[TEST] (@id int, @table_name nvarchar(50))
AS
BEGIN
    declare @strSQL NVARCHAR(MAX)

    set @strSQL = ' SELECT ' + cast(@id as varchar(20)) + ', Name from ' + @table_name
    exec(@strSQL)
END

and run that SP by

EXEC [TEST] @id=5, @table_name='tablename'  
Sign up to request clarification or add additional context in comments.

9 Comments

I guess this is the only way. The only problem is that the str can only be 4000 char and I need it to be much bigger. Thanks anyways!
where you faced problem of 4000 chars ? In string you just pass table name, right ?
This was just an example. The one I want to create is much larger than that :) BTW can i skip the declare @strSQL and just to a SELECT directly in the store procedure??
Then you can use VARCHAR(MAX) or NVARCHAR(MAX) for large strings
Yes but my max is 4000 characters. Could I create a store procedure and mix your solution with just plain select like declare (at)strSQL NVARCHAR(MAX) set (at)strSQL = ' SELECT ' + cast((at)id as varchar(20)) + ', Name from ' + (at)table_name exec((at)strSQL) UNION ALL select id, name from table2
|

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.