復制代碼 代碼如下:
DECLARE @strSQL VARCHAR(8000)
SET @strSQL = 'SELECT t.STUNAME [姓名]'
SELECT @strSQL = @strSQL + ',SUM(CASE s.SNAME WHEN ''' + SNAME + ''' THEN g.[Score] END) [' + SNAME + ']' FROM (SELECT SNAME FROM [Subject]) AS tmp
SELECT @strSQL = @strSQL + ' FROM [Score] g,[Subject] s, [Student] t WHERE g.SID=s.SID AND g.STUID = t.STUID GROUP BY t.STUID, t.STUNAME'
EXEC(@strSQL)
SQL SERVER 2005 中,已經有實現此功能的內置方法了。