通过转置行sql server来设置带有变量列的结果集

时间:2011-01-06 02:58:09

标签: sql sql-server tsql

我有一个SQL语句,用于创建一个具有可变列数的结果集,它可以正常工作,但性能不佳。我认为这是因为我正在使用动态SQL和Cursor。我正在寻找任何替代解决方案,以使其性能更好。 任何想法将不胜感激

感谢

declare @grpId int = 1

SET NOCOUNT ON;

Declare @Script as Varchar(max);
Declare @Script_prepare as Varchar(max);


create table myTable ([measId] [int], [valSeq] [int])

IF  (Not EXISTS (SELECT * FROM tbl_group WHERE grpId = @grpId))
BEGIN
    PRINT 'Failed to create Group Dataset'
    RETURN 
END

Set @Script_prepare = 'Alter table  myTable Add [?] varchar(max); '
set @Script = ''

DECLARE  @iMeasId  int, @iSeq int

DECLARE @delimiter char;
set @delimiter = ',';

SELECT @Script = COALESCE(@Script , '')+ Replace(@Script_prepare, '?', Replace(parmName, ' ', ''))
FROM  tbl_parameter AS parm INNER JOIN
               tbl_group AS grp ON parm.grpId = grp.grpId
where grp.grpId = @grpId
Exec (@Script)

select @Script = 'DECLARE crsrParm CURSOR FOR
    SELECT 
        meas.measId
        , val.valSeq
    from tbl_measurement as meas inner join tbl_value as val on val.measId = meas.measId
    where grpId = ' + STR(@grpId)
    + ' group by meas.measId, val.valSeq'
    + ' order by meas.measId, val.valSeq'

Exec (@Script)

open crsrParm
fetch crsrParm into @iMeasId, @iSeq 
WHILE @@Fetch_Status = 0
BEGIN
    set @Script = 'INSERT myTable VALUES ('
        + str(@iMeasId) + ',' + str(@iSeq)
        + (
            SELECT ','''+COALESCE(val.valValue , ' ')+ ''''
            FROM (select * from [KNRD_GED].[dbo].[tbl_value] where measId = @iMeasId and valSeq = @iSeq) as val
            right join tbl_parameter as parm on parm.parmId = val.parmId
            where parm.grpId = @grpId
            FOR XML PATH('') 
        ) 
        + ') '
    exec(@Script)
    fetch crsrParm into @iMeasId, @iSeq 
END

CLOSE crsrParm
DEALLOCATE crsrParm
select * from myTable

0 个答案:

没有答案