How can we extract the value from a stuff function variable for processing

299 views Asked by At

Hello I would like to know how can we assign the value of a column to a variable in SQL server 2012

For example consider the below scenario in which I retrieve the record id and emails (multiple emails as comma separated in single row) for a list of persons mentioned in a multi person field in a form The spd looks like following (contains many joins) A sample structure of the entire spd is as follows .

BEGIN
DECLARE @VAR1 VARCHAR(50)
DECLARE @VAR2 VARCHAR(50)
DECLARE @FINAL NVARCHAR(MAX)
DECLARE @DEFAULT VARCHAR(50)
SET @DEFAULTE = '[email protected]'

select  @var1 = isnull( email,@DEFAULTE) from usertable inner join userdet on 
                 usertable .recid = userdet.recid and usertable.uid=1 

SET @var2 = isnull (email,@DEFAULTE)  from usertable inner join userdet on 
            usertable .recid = userdet.recid and usertable.uid=1  
SET @FINAL= @var1 + "," +@var2


SELECT FORM.RECORD ID AS [RECORD ID],
       PRODUCT.DESCRIPTION AS [DESCRIPTION],
       SUP.NAME AS [SUPPLIER],
    --  @FINAL AS [FINALEMAILS]
       ABC AS [RESULTEMAILS]
     
     FROM DB1.FORM F INNER JOIN
          DB1.PROJTYPE P
          ON F.RECORDID= P.RECORDID
      LEFT OUTER JOIN
       (select Sup.formid,Supdet.name
       From DB1.Formdet fdet
       inner join DB1.Form Fo on Fo.recordid= Sup.formid)SupRec
       On RecSup.formid = form.recordid
       LEFT OUTER JOIN 
       ( Select FData.Formid,FDDesc.description 
       From DB1.FormDetails FData , DB1.FormDesc F
       on Fdata.formid= F.Formid) Desc on Desc.Formid= form.recordid
     
LEFT OUTER JOIN
(SELECT distinct formid , abc= STUFF((Select ',' + a.email from Db1.User b, 
Db1.formfields c
DB1.Userdetails a, DB1.FormRecordmapping d
where
where b.UserAddressid= a.id
and d.formfieldid= c.id
and b.Userid= d.FormValue
and c.id='3000'
and d.formid = ep.id
FOR XML PATH (''),TYPE).value('text()[1]','nvarchar(max)'),1,1,'') 
FROM [DB1.FORMRecordmapping ep) OPS
on OPS.formid= formid
WHERE  F.NOTIFREQ ='yes'
AND P= 300
END

Sample output shows as :

Record Id     Descripton  Supplier  ResultEmails
---------------------------------------------------------------------------------
22222          DescrTest   Sup1     [email protected],[email protected],[email protected]
33333          DescTest2   Sup2     [email protected]
-------------------------------------------------------------

My requirement is: How can I achieve assigning the value (comma separated list of emails) returned by the stuff function in the above code to a string variable (varchar or nvarchar type) for further processing , without modifying too much of above code?. Any help would be appreciated. Thanks

0

There are 0 answers