Dynamic SQL from within a Table Valued function?

  • Is it possible to execute a dynamically generated sql string from inside a user defined table valued function?

    I know I can't use EXEC sp_executesql @sql, but are there any alternatives?

    Thanks in advance.

    Bob

    http://www.bluemulesoftware.com


    Regards,
    Bob Szymanski
    Blue Mule Software

  • Perhaps give an example of what you're trying to do (even if it won't work)?

  • From w/in the function I'd like to pass in a string of sql and prepend and append some text and then execute it. This executed statement is used to fill a table variable. For example:

    SET ANSI_NULLS ON

    GO

    SET QUOTED_IDENTIFIER ON

    GO

    ALTER FUNCTION [dbo].[GenerateFolderNodeText]

    (

    @strSQL VARCHAR(MAX)

    )

    RETURNS

    @Results TABLE

    (

    -- Add the column definitions for the TABLE variable here

    ID INT,

    NodeText VARCHAR(8000)

    )

    AS

    BEGIN

    DECLARE @sql VARCHAR(8000)

    -- Temp table variable to store raw query results with an ID

    DECLARE @raw TABLE

    (

    ID int IDENTITY(1,1),

    RawText VARCHAR(8000)

    )

    SET @sql = 'INSERT INTO @raw (RawText)' + @strSQL + ' ORDER BY RawText'

    EXEC(@SQL)

    .

    .

    .

    RETURN

    END


    Regards,
    Bob Szymanski
    Blue Mule Software

  • Ok, I understand this isn't possible according to BOL. Bummer!

    I moved it to a stored procedure and now it works. I'll need to be careful in terms of security due to the possibility of injection attacks, etc. I'll need to specify explicit/strict execute privs.

    Now that it's stored procedure I had to make a change though, In order for it to recognize the @raw table I had to call it like this:

    INSERT INTO @raw(RawText) EXECUTE sp_executesql @strSQL

    Bob

    http://www.bluemulesoftware.com


    Regards,
    Bob Szymanski
    Blue Mule Software

  • this is very dangerous from a security perspective.  anyone with perms to execute this proc can wreak all sorts of havoc.

    you might want to read this: http://www.sommarskog.se/dynamic_sql.html

    ---------------------------------------
    elsasoft.org

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply