declare @s varchar(8000)
declare @i int
set @i=1
set @s='select comm_createdby,month(comm_createddate) as cmonth '
while @i<31
begin
  set @s=@s+',(case day(comm_createddate) when '+cast(@i as varchar(10))+' then count(day(comm_createddate)) else 0 end) as '''+cast(@i as varchar(10))+''''+char(10)
  set @i=@i+1
end
exec(@s+'from communication where comm_deleted is null group  by day(comm_createddate),month(comm_createddate),comm_createdby')

解决方案 »

  1.   

    动态SQL不可以,用存储过程。
      

  2.   

    create proc p
    as
    declare @s varchar(8000)
    declare @i int
    set @i=1
    set @s='select comm_createdby,month(comm_createddate) as cmonth '
    while @i <31
    begin
      set @s=@s+',(case day(comm_createddate) when '+cast(@i as varchar(10))+' then count(day(comm_createddate)) else 0 end) as '''+cast(@i as varchar(10))+''''+char(10)
      set @i=@i+1
    end
    exec(@s+'from communication where comm_deleted is null group  by day(comm_createddate),month(comm_createddate),comm_createdby')
      

  3.   

    看一下3楼的,当然也可以向PROC传参数。
      

  4.   

    可以先创建一个与查询结果一样的表结构,

    INSERT INTO TB EXEC()CREATE VIEW VIEW_TB
    AS 
    SELECT * FROM TB
      

  5.   

    可以先创建一个与查询结果一样的表结构,

    INSERT INTO TB EXEC()CREATE VIEW VIEW_TB
    AS 
    SELECT * FROM TB
    [/Quote]除了创建一个与查询结果一样的表结构,还有什么好的方法吗?谢谢