Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I work on sql server 2014 I need to run this statement below dynamically without

using group id static

because I don't know make group id using may be 10,15,20

so How to run query below dynamically without write static group id on join?

sql fiddle i will work on it
SQL Server 2014 | db<>fiddle[^]

What I have tried:

SQL
select r1.familyid, r1.companyid, r1.GlobalPnId,
     concat(
         r1.PortionKey,
         r2.PortionKey,
         r3.PortionKey,
         r4.PortionKey,
         r5.PortionKey,
         r6.PortionKey,
         r7.PortionKey,
         r8.PortionKey,
         r9.PortionKey
         ) as PartNumber
 from GetFinalResult r1
 left join GetFinalResult r2 on r2.familyid = r1.familyid and r2.GroupID = 2
 left join GetFinalResult r3 on r3.familyid = r1.familyid and r3.GroupID = 3
 left join GetFinalResult r4 on r4.familyid = r1.familyid and r4.GroupID = 4
 left join GetFinalResult r5 on r5.familyid = r1.familyid and r5.GroupID = 5
 left join GetFinalResult r6 on r6.familyid = r1.familyid and r6.GroupID = 6
 left join GetFinalResult r7 on r7.familyid = r1.familyid and r7.GroupID = 7
 left join GetFinalResult r8 on r8.familyid = r1.familyid and r8.GroupID = 8
 left join GetFinalResult r9 on r9.familyid = r1.familyid and r9.GroupID = 9
 where r1.GroupID = 1
Posted
Updated 1-Jun-21 3:03am

1 solution

You can use a variable in the query. The value for the variable can for example come from a parameter if this is a stored procedure. See DECLARE @local_variable (Transact-SQL) - SQL Server | Microsoft Docs[^]

As an example, consider the following excerpt
SQL
declare @groupid int;
set @groupid = 1;

select r1.familyid, r1.companyid, 
...
 where r1.GroupID = @groupid
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900