日期:2014-05-19  浏览次数:20561 次

初学动态SQL;帮我解释一下这个相对简单的动态SQL
数据库里:
DepartName   Date1  
001                 2007-5-1  
001                 2007-5-2  
001                 2007-5-3  
001                 2007-5-4  

但在前台的显示效果我却想要  

001   2007-5-1   2007-5-2   2007-5-3   2007-5-4
-------------
create   table   tt(DepartName   varchar(10),Date1   datetime)
insert   tt   select   '001 ', '2007-5-1 '
union   all   select   '001 ', '2007-5-2 '
union   all   select   '001 ', '2007-5-3 '
union   all   select   '001 ', '2007-5-4 '

declare   @s   varchar(8000)
set   @s= 'select   DepartName '
select   @s=@s+ ',max(case   DepartName   when   ' ' '+DepartName+ ' ' '   then   Date1   else   null   end)as   [ '+convert(varchar(10),Date1,120)+ '] '
from   tt   group   by   DepartName,Date1
select   @s=@s+ '   from   tt   group   by   DepartName '
select   @s
exec(@s)

问题:
1。case   DepartName   when   ' ' '+DepartName+ ' ' '   then   Date1   else   null   end   这个好象是个模式。。。怎么理解?
2。as   [ '+convert(varchar(10),Date1,120)+ '] ',中括号是不是为了防止与关键字重名的?

3。还有什么地方要注意的,请大家指点,谢谢了



------解决方案--------------------
好像你的语句并不对

2中括号是括起一个标志符,可以在中括号中间存在空格以及特殊字符