Click here to Skip to main content
15,893,814 members
Please Sign up or sign in to vote.
2.00/5 (3 votes)
See more:
In table records as follows
TTDate Course Sess Topic Staff
 
Aug2   Eng     1   Rev   Mj
Aug2   Tam     2   Maj   Mj
Aug2   Mat     3   Tom   Mj

From my above table i want output as follows
Dear Mj, Aug2(Eng -Rev/1,Tam -Maj/2,Mat -Tom/3)

For that i written a stored procedure as follows
SQL
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER proc [dbo].[OH_TimeTable] 
as 

DECLARE @MyString VARCHAR(MAX)

SET @MyString = ''

SELECT @MyString = COALESCE(@MyString + ',', ' ')  +[TTDate] + [Course]  + [Sess]  +[Topic] 
 from Tb_Sch_Time_Table where  Active <> 'D' 

SELECT @MyString as MyString

When i execute the stored procedure output as follows
,Aug2 Eng 1 Rev,Aug2 Tam 2 Maj,Aug2 Mat 3 Tom

But i want the stored procedure output as follows
Dear Mj, Aug2(Eng -Rev/1,Tam -Maj/2,Mat -Tom/3) 

please help me from my above stored procedure. what is the mistake i made.
Posted
Updated 28-Aug-14 1:24am
v3

SQL
SET @MyString = 'Dear'

SELECT @MyString = COALESCE(@MyString + Staff, ' ') + ',(' +[TTDate] + [Course] + [Sess] +[Topic] + ')'
from Tb_Sch_Time_Table where Active <> 'D'
 
Share this answer
 
try the below code
SQL
declare @str varchar(100), @staff varchar(800), @finalstr varchar(1000)
select @staff = ltrim(rtrim(Staff)), @str = ltrim(rtrim(Convert(char(7),sch1.[TTDate],100)))+'('+STUFF(
(select ','+ ltrim(rtrim([Course])) +'-'+ LTRIM(rtrim(topic)) +'/'+ ltrim(rtrim([Sess])) from Tb_Sch_Time_Table sch
where sch.TTDate = sch1.TTDate
FOR XML PATH(''))
,1,1,'')+')' from Tb_Sch_Time_Table sch1 where Active <> 'D' 
group by TTDate, Staff
order by 1

set @finalstr = 'Dear '+@staff+', '+@str
print @finalstr
 
Share this answer
 
v2

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