Assigning the result of dynamic SQL to the result in a function

I have the following stored procedure:

CREATE PROCEDURE spInfoSchemaTableList
    (
    @DB nvarchar(30)
    )
AS
--- Set SQL Environment Variables
SET NOCOUNT ON

--- Initialize Stored Procedure

    DECLARE @SQL nvarchar (2000), @DB2 nvarchar(32)
    SET @DB2 = N'[' + @DB + ']'

    SET @SQL = N'SELECT TABLE_NAME FROM ' + @DB2 + '.INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = '  + CHAR(39) + 'BASE TABLE' + CHAR(39) + 'AND TABLE_NAME <> ' + CHAR(39) + 'dtproperties' + CHAR(39) + ' ORDER BY TABLE_NAME'
    EXEC (@SQL)
 
SP_EXIT:
  RETURN

Is there a way to convert this into a function so that when given a database it will return a list of tables?
Is there also a way to asign the EXEC (@SQL) to a table variable?

Thanks,

Tom
TomCouryOwnerAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Anthony PerkinsCommented:
>>Is there a way to convert this into a function so that when given a database it will return a list of tables?<<
If you mean a function, as in a User Defined Function (UDF), than the answer is no:  You cannot use dynamic SQL in UDF's

>>Is there also a way to asign the EXEC (@SQL) to a table variable?<<
You can insert the values to a temporary table, as in:
CREATE TABLE #MyTempTable (TableName varchar(50))

...

INSERT INTO #MyTempTable EXEC (@SQL)

...

DROP TABLE #MyTempTable

and then copy those to a variable of type table. Although the second step seems like over-kill.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
TomCouryOwnerAuthor Commented:
Thanks... That's what I was afraid of...
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.