Posts Tagged ‘dynamic query’

declare @tablename nvarchar (100)
set @tablename = ‘party’
 
declare @query nvarchar (1000)
set @query= ‘select top 10 * from ‘ + @tablename
exec (@query )
— Get the dynamic query value assigned to a outer variable
DECLARE @RsDataSQL nvarchar(2000)=‘select top 1 @Rstable2 = ”RS_” + rc.TablePrefix + ”_” + rf.TablePrefix + ”_EventType”’
       +‘ from RControl rc 
      inner join Form rf  on rf.FormId=rc.FormId
      where rf.partyid = 49310′            
 
declare @lrstable nvarchar (500) =
exec sp_executesql @RsDataSQL, N’@Rstable2 nvarchar(500) out’, @lrstable out
 
select @lrstable
— another example
declare @tablename nvarchar (100)
set @tablename = ‘party’
 
declare @query nvarchar (1000)
set @query= ‘select top 1 @partyid = partyid from ‘ + @tablename
 
declare @partyid1 int =
exec sp_executesql @query, N’@partyid int out’, @partyid1 out
 
select @partyid1