0

我有以下 MySQL:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'sum(case when perm = ''',
      perm,
      ''' then 1 else 0 end) AS ',
      perm
    )
  ) INTO @sql
FROM perms;

SET @sql = CONCAT('SELECT role, ', @sql, ' 
                  FROM perms 
                   GROUP BY role');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

但是,我必须使用 Sybase 12,有人知道如何转换吗?

4

1 回答 1

1

试试这个:

declare cur_perm cursor for 
select perm from perms
go
declare @sql  varchar(4000) 
declare @perm varchar(4000) 

set @sql = ' '


open cur_perm
fetch cur_perm into @perm
while @@sqlstatus=0 begin
  select @sql = @sql+'sum(case when perm = '''+@perm+''' then 1 else 0 end) AS '''+@perm+''', '
  fetch cur_perm into @perm
end
close cur_perm
deallocate cursor cur_perm

select @sql = 'SELECT '+ @sql+' role 
                  FROM perms 
                   GROUP BY role'

exec(@sql)
于 2012-11-22T11:59:07.477 回答