views:

46

answers:

2

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

UPDATE Please read what I've written where is the problem:

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:

+5  A: 

If you are using SQL Server 2005 or 2008, you could use a Common Table Expression instead of creating a temporary table.

Common Table Expressions

Your CTE should look like:

WITH Records (ROWGUID) AS ( 
    SELECT ROWGUID 
      FROM MySimpleTable 
) 

Then you can simply use:

SELECT ROWGUID 
  FROM myTable 
 WHERE ROWGUID IN (SELECT ROWGUID 
                     FROM Records);

Which potentially means you can drop your Variable.


EDIT

Ok, so CTE is out of the question. But, what about using a Table variable instead of creating a Temporary Table.

DECLARE @myVar nvarchar(max);

DECLARE @table TABLE
(
    ROWGUID uniqueidentifier
)

SET @myVar = 'SELECT ROWGUID FROM MySampleTable';

INSERT INTO @table
  EXEC sp_executesql @myVar;

SELECT ClientID
  FROM myTable
 WHERE EXISTS (SELECT ClientID FROM @table);
Ardman
I've tried to use it but it does not work:DECLARE @MyVariable nvarchar(max)SET @MyVariable = 'SELECT ROWGUID FROM MySimpleTableWITH Records (ROWGUID) AS (exec sp_executesql @MyVariable )SELECT ROWGUID FROM myTable WHERE ROWGUID in (Records)
niao
Have edited answer to use code block :o)
Ardman
but how can I execute the statement exec sp_executesql @MyVariable ?? @MyVariable stores for instance a query like this: SELECT ROWGUID FROM MySimpleTable
niao
How can I use "exec sp_executesql @MyVariable " inside this CTE?
niao
The CTE will now store everything that is in your Variable.
Ardman
but I have to use variable. I don't know what kind of sql query will be generated and included in Variable. I only know what kind of field from what kind of column will be returned
niao
+1  A: 

Maybe you could use User Defined Functions instead of stored procedures?

MadBoy