I have two tables. First one is student table where he can select two optional courses and other table is current semester's optional courses list.
When ever the student selects a course, row is inserted with basic details such as roll number, inserted time, selected course and status as "1". When ever a selected course is de-selected the status is set as "0" for that row.
Suppose the student has select course id 1 and 2.
Now using this query
select SselectedCourse AS [text()] FROM Sample.dbo.Tbl_student_details where var_rollnumber = '020803009' and status = 1 order by var_courseselectedtime desc FOR XML PATH('')This will give me the result as "12" where 1 is physics and 2 is social.
the second table holds the value from 1-9 For e.g course id
1 = physics 2 = social 3 = chemistry 4 = geography 5 = computer 6 = Spoken Hindi 7 = Spoken English 8 = B.EEE 9 = B.ECEnow the current student has selected 1 and 2. So on first column, i get "12" and second column i need to get "3456789"(remaining courses). How to write a query for this?
This is not in single query but is simple.
DECLARE @STUDENT AS TABLE(ID INT, COURSEID INT) DECLARE @SEM AS TABLE (COURSEID INT, COURSE VARCHAR(100)) INSERT INTO @STUDENT VALUES(1, 1) INSERT INTO @STUDENT VALUES(1, 2) INSERT INTO @SEM VALUES(1, 'physics') INSERT INTO @SEM VALUES(2, 'social') INSERT INTO @SEM VALUES(3, 'chemistry') INSERT INTO @SEM VALUES(4, 'geography') INSERT INTO @SEM VALUES(5, 'computer') INSERT INTO @SEM VALUES(6, 'Spoken Hindi') INSERT INTO @SEM VALUES(7, 'Spoken English') INSERT INTO @SEM VALUES(8, 'B.EEE') INSERT INTO @SEM VALUES(9, 'B.ECE') DECLARE @COURSEIDS_STUDENT VARCHAR(100), @COURSEIDS_SEM VARCHAR(100) SELECT @COURSEIDS_STUDENT = COALESCE(@COURSEIDS_STUDENT, '') + CONVERT(VARCHAR(10), COURSEID) + ' ' FROM @STUDENT SELECT @COURSEIDS_SEM = COALESCE(@COURSEIDS_SEM , '') + CONVERT(VARCHAR(10), COURSEID) + ' ' FROM @SEM WHERE COURSEID NOT IN (SELECT COURSEID FROM @STUDENT) SELECT @COURSEIDS_STUDENT COURSEIDS_STUDENT, @COURSEIDS_SEM COURSEIDS_SEM