Execute query stored in variable in a very specific way

Posted by niao on Stack Overflow See other posts from Stack Overflow or by niao
Published on 2010-05-21T08:21:07Z Indexed on 2010/05/21 8:30 UTC
Read the original article Hit count: 169

Filed under:
|

Greetings, I have a problem as follows: I have an SQL variable declared:

DECLARE @myVariable nvarchar(max)

a third party library set a value for this variable. To simplify, lets say that the value is as follows:

SET @myVariable = 'Select ROWGUID from MySampleTable'

Now, I want to execute the following query:

SELECT ROWGUID FROM myTable WHERE ROWGUID in (exec sp_executesql @myVariable )

However, the above statement does not work because it returns an error telling me that I can't execute stored procedure in that way. I made a workaround and this is what I wrote:

create table #temptable (ID uniqueidentifier null)
if(@myVariable is not null AND @myVariable !='') insert into #temptable exec  sp_executesql @myVariable 

SELECT ROWGUID FROM myTable WHERE ROWGUID in (select * from #temptable) 
DROP TABLE #temptable

This works fine.However I don't think it is a good idea to use temporary table. How can I achieve the same result without necessity of creating temporary tables?

I am using SQL SERVER 2005

© Stack Overflow or respective owner

Related posts about sql

Related posts about sql-server-2005