SQL SERVER 中 动态 SQL

关于动态SQL,我们日常看到的例子是:

create table scores(stdname varchar(20),stdsubject varchar (20),score int)

insert into scores (stdname,stdsubject,socre) values ('wing','数学',60);

insert into scores (stdname,stdsubject,socre) values ('wing','语文',60);

insert into scores (stdname,stdsubject,socre) values ('wing','物理',70);

insert into scores (stdname,stdsubject,socre) values ('kobe','语文',60);

insert into scores (stdname,stdsubject,socre) values ('kobe','物理',70);

insert into scores (stdname,stdsubject,socre) values ('kobe','数学',90);

通常我们用 select stdname,stdsubject,socre from scores查出来的结果是:

这样显然不直观,我们希望得到这样的查询结果:

而要查询这样的结果我们可以用以下的SQL 语句:

select stdname,

sum (case stdsubject when '数学' then score else 0) '数学',

sum (case stdsubject when '语文' then score else 0) '语文',

sum (case stdsubject when '物理' then score else 0) '物理'

from scores

group by stdname...

不过这样不能完全解决问题,因为科目的是不断增加的,我们不可能写类似按照这种模式去写SQL,这时就需要动态SQL了,

动态SQL是指在程序运行时动态地创建语句、对语句进行语法分析并执行该语句。

现在,我们的问题出现在如何确定出成绩表的科目,那么我们可以用一个简单的SQL 语句查询出来,select distinct stdsubject from scores,结果是:

 

那现在的问题是,如何将查询出来的结果拼接到sum(case...when..then..else end)中了,我们可以用字符串连接,

定义一个字符串变量 declare @strSql varchar(8000)--最大长度

然后

      set @strSql = '' 

      select @strSql = @strslq + 'sum (case stdsubject when '''+stdsubject+''' then score else 0 end) '+stdsubject+''    

       from (select distinct stdsubject from scores) as temp

       print @strSql

就这可以得以下的结果:

sum (case stdsubject when '数学' then score else 0 end) 数学

sum (case stdsubject when '物理' then score else 0 end) 物理

sum (case stdsubject when '语文' then score else 0 end) 语文

现在可以动态生成我们想要的语句,最后我们跟group by子句拼接,得到的语句是:

 

declare @strSql varchar(8000)--最大长度

          set @strSql= 'select stdname'

          select @strSql = @strSql + ',sum (case stdsubject when '''+stdsubject+''' then score else 0 end) '+stdsubject+''    

          from (select distinct stdsubject from scores) as temp

          set @strSql = @strSql + ' from scores group by stdname'

          print @strSql

          exec(@strSql)

最后执行exec,就可以得我们想要的结果了。

其中,exec可以执行标量值的用户定义函数、系统过程、用户定义存储过程或扩展存储过程。同时支持 Transact-SQL 批处理内的字符串的执行。

posted @ 2010-01-06 14:30  桑叶舟  阅读(402)  评论(1编辑  收藏  举报