Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic sql using table variable -TSQL

My problem is using a table variable in a exec.

declare @sort_col nvarchar(1000) = 'itm_id'
declare @sort_dir nvarchar(4) = 'desc'
declare @filters nvarchar(1000) = ' and itm_name like ''%aa%'''

declare @temp table
(
 itm_id int
)

insert into @temp
EXEC('select itm_id from Tblitm where itm_name not like ''%aa%''')

EXEC('select * from (select (ROW_NUMBER() OVER (ORDER BY '+@sort_col+' '+@sort_dir+')) row_num, * FROM (select itm_id, itm_name, 
dbo.fnItmsHistory(itm_id) itm_history
         from dbo.Tblitm as itm
         left outer join '+@temp+' as temp on itm.itm_id = temp.itm_id
         where itm_id=itm_id and temp.itm_id = null '+@filters+') as x) as tmp')

It says Must declare the scalar variable "@temp" when the temp table is declared i tried using original temp table and it worked, but i had problems when trying to update my entity model.So is there any solution for this problem?

Note: I must use exec because in filters i store string for the where clause.

like image 642
Aleks Avatar asked May 20 '13 16:05

Aleks


1 Answers

Try moving the table variable inside the dynamic statement.

EXEC('
declare @temp table
(
 itm_id int
)
insert into @temp
select itm_id from Tblitm where itm_name not like ''%aa%''
select * from (select (ROW_NUMBER() OVER (ORDER BY '+@sort_col+' '+@sort_dir+')) row_num, * FROM (select itm_id, itm_name, 
dbo.fnItmsHistory(itm_id) itm_history
         from dbo.Tblitm as itm
         left outer join @temp as temp on itm.itm_id = temp.itm_id
         where itm_id=itm_id and temp.itm_id = null '+@filters+') as x) as tmp')
like image 159
Magnus Avatar answered Nov 18 '22 23:11

Magnus