Quantcast
Channel: SQLServerCentral » SQL Server 2014 » Development - SQL Server 2014 » Latest topics
Viewing all articles
Browse latest Browse all 3145

Loop through records in a table and use the same dynamically

$
0
0
Hi All, I have a requirement to prepare the sql dynamically in order to use the table record values in joins.Sample data as below. CREATE TABLE tmpConfig ( Action VARCHAR(255), Dimension VARCHAR(255), Field VARCHAR (255), Hierarchy VARCHAR(255), Level VARCHAR(255), Value VARCHAR(255) )insert into tmpConfig (Action,Dimension,Field,Hierarchy,Level,Value) select 'Exclude','Brand','Brand_id','mart.t_mart_isscom_trademark_hier','Brand_id','2675,612' union all select 'Include','Product','Product_id','mart.t_mart_isscom_trademark_hier','Product_id','675,162'I have to read the tmpConfig table (above) record by record then assign the value to a variable.For example: My first records is like below[b]Action Dimension Field Hierarchy Level Value[/b]Exclude Brand Brand_id trademark_hier Brand_id 2675,612If "Action" is Exclude it should replace with "not In" ,Include - In ,then assign this to one variable(@action).If dimension = Brand then @dim = 'Brand', @filed = field,@val = value from tmpConfigI have to use those variables dynamically in my query as below: (Syntax may be in correct)select * from Xtable xInner Join '+@dim+' a with (nolock)ON x.ID = a.'+@field+' where '+@field+' '+@action+'('+@val+')[b]Can anyone can help me on how to get these?[/b]

Viewing all articles
Browse latest Browse all 3145

Trending Articles