How can I Execute an insert statement that is dynamically created?

  • [font="Comic Sans MS"]

    Hi All,

    I would like to know how can I execute an insert statement that is dynamically created?

    I know that there is a system sp "sp_sqlexec". I call it using a piece of code like the following:

    declare @my_final_sql varchar(MAX);

    set @my_final_sql = 'insert into tablea (col1, col2) select col1, col2 from '

    declare @my_view varchar(MAX);

    set @my_view = 'view1';

    set @my_final_sql = @my_final_sql + @my_view;

    exec sp_sqlexec @my_final_sql;

    However, this gives me the error:

    Only functions and extended stored procedures can be executed from within a function.

    So, is there any solution to my problem?

    Note: I forgot to say that I call the above piece of code from within a function. Is the problem around there?

    [/font]

  • Yes. There is a problem.

    User defined functions does not allow dynamic execution of SQL.

    I think you will have to use CLR or work around with other options.

    Regards,

  • [font="Comic Sans MS"]

    Thank you for the answer.

    I will try CLR. BTW, what do you have in your mind when saying about other options?

    [/font]

  • I will see if i really need to use UDF.

    Else i will call the code from a stored proc.

    Regards,

  • Ok. Thanks a lot for your answers.

    BR

    Panayotis Matsinopoulos

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

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