RetroCoder
RetroCoder

Reputation: 2685

How do I create t-sql from a string

I have a string variabled declared as so:

declare @myGeniuses as nvarchar(8000);
set @myGeniuses = ' in (1,2,3)';

I want to apply my variable in a select statement like so:

select * from GENIUSES where GeniusId @myGeniuses

Upvotes: 0

Views: 86

Answers (3)

Lori Lalonde - MSFT
Lori Lalonde - MSFT

Reputation: 368

You will need to use sp_executesql to achieve that result which lets you pass in your query statement as a string and executes it.

See this for more details: http://msdn.microsoft.com/en-us/library/ms188001.aspx

Example usage:

DECLARE @sql AS NVARCHAR(MAX); 
DECLARE @filter AS NVARCHAR(500); 
SET @filter = ' in (1,2,3)'; 
SET @sql = 'select * from GENIUSES where GeniusId' + @filter; 
EXECUTE sp_executesql @sql; 

Upvotes: 1

Rodolfo
Rodolfo

Reputation: 4183

you would do ...

exec ('select * from GENIUSES where GeniusId' + @myGeniuses)

Upvotes: 1

Royi Namir
Royi Namir

Reputation: 148624

declare @t nvarchar(max)
set @t='select * from GENIUSES where GeniusId'+ @myGeniuses

exec @t

Upvotes: 1

Related Questions