简体   繁体   中英

SQL Server cursor to pull data from different tables and merge the same lines

I am using SQL Server 2014.

Student databse:

  • notlar (@vize, @ders_id, @ogrenci_id)
  • ogrenciler (@id, @isim)
  • dersler (@ders_adi, @ders_id)

There are tables and columns in the form of the student's visa notes with the cursor and the course is listed in the course name.

The output is as follows:

Select 
    o1.adi , n1.vize, d1.ders_adi 
from 
    ogrenci o1, notlar n1, dersler d1 
where 
    o1.Ogr_ID = n1.Ogr_ID 
    and convert(varchar(22), n1.Ders_Kod) = convert(varchar(22), d1.Ders_Kod)  
order by 
    adi

DECLARE @adi NVARCHAR(MAX), @vize NVARCHAR(MAX), @ders NVARCHAR(MAX) 

DECLARE CRS_bolumler CURSOR FOR
    SELECT 
        o1.adi , n1.vize, d1.ders_adi 
    FROM
        ogrenci o1, notlar n1, dersler d1 
    WHERE
        o1.Ogr_ID = n1.Ogr_ID 
        AND CONVERT(VARCHAR(22), n1.Ders_Kod) = CONVERT(VARCHAR(22), d1.Ders_Kod) 
    ORDER BY
        adi

OPEN CRS_bolumler

FETCH NEXT FROM CRS_bolumler INTO @adi, @vize, @ders 

WHILE @@FETCH_STATUS =0
BEGIN   
    PRINT @adi + ',' + @vize + ',' + @ders

    FETCH NEXT FROM CRS_bolumler INTO @adi, @vize,@ders
END

CLOSE CRS_bolumler 
DEALLOCATE CRS_bolumler

Messages:

 {Ali,60,Bilg. Müh. Giriş    
    Ali,50,Alg ve Prog-I       
    Ali,40,Matematik-I         
    Betül,30,Bilg. Müh. Giriş    
    Betül,30,Alg ve Prog-I       
    Betül,20,Matematik-I         
    Bilal,70,Bilg. Müh. Giriş    
    Bilal,80,Alg ve Prog-I       
    Bilal,90,Matematik-I         
    Feyza,80,Bilg. Müh. Giriş    
    Feyza,60,Alg ve Prog-I       
    Feyza,40,Matematik-I         
    Leyla,20,Bilg. Müh. Giriş    
    Leyla,30,Alg ve Prog-I       
    Leyla,20,Matematik-I }      

I'm getting a printout. My request is to get the visa name and course name of the students with the same names as follows:

{Ali,60,Bilg. Müh. Giriş ,50,Alg ve Prog-I   ,40,Matematik-I         
Betül,30,Bilg. Müh. Giriş ,30,Alg ve Prog-I ,20,Matematik-I         
Bilal,70,Bilg. Müh. Giriş ,80,Alg ve Prog-I  ,90,Matematik-I         
Feyza,80,Bilg. Müh. Giriş  ,60,Alg ve Prog-I ,40,Matematik-I         
Leyla,20,Bilg. Müh. Giriş,30,Alg ve Prog-I ,20,Matematik-I }  

Solution of the problem:

select o.isim, 
       stuff((
            select ', ' + ltrim(str(n.vize)) + ', ' + d.ders_adi
            from notlar n
            inner join dersler d on n.ders_id = d.ders_id
            where n.ogrenci_id = o.id
            FOR XML PATH('')
            ), 1, 2, '') as vizeler
from ogrenciler o;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM