mdxsql-server-2016openrowsetsp-executesql

How do I execute a dynamic SQL with over 8000 Characters?


I'm trying to execute a stored procedure that merges SQL with MDX data by using this code:

OPENROWSET('MSOLAP',..)-Function.

I do this by building a string inside the stored procedure and executing it like this

EXEC sp_executesql @sqlQuery

When I do that, however, I get the error mentioned in the title when @sqlQuery exceeds 8000 characters

The OPENROWSET() part is executing the MDX query and according to the error this is also the part that exceeds the 8000 character limit, due to the number of Ids in the @MDXEntityIdSet parameter.


SET @SQLMDXQuery=
  'with MQ
  (
    Datum
   ,Messwert
   ,Schlüssel
   ,MDXName
  )
  as
  (
  SELECT   
    convert(DATETIME,"[Measures].[DateTimeKey]")
    ,convert(FLOAT,"[Measures].[KPIValue]")
    ,convert(nvarchar(max),"[Measures].[EntityKey]")
    ,convert(nvarchar(max),"[Measures].[EntityName]")  
  FROM        
    OPENROWSET(''MSOLAP'',''Persist Security Info=False;Data Source=dwh-test-50-sql; Catalog='+@DBCatalog+';'',';
    --OPENQUERY(SSAS,';

set @MDXPart=convert(nvarchar(max),
  '''WITH
    MEMBER [Measures].[DateTimeKey] AS '+@MDXShortDateTimeKey+'.CurrentMember.Properties("KEY")
    MEMBER [Measures].[KPIValue] AS '+@MDXAggregation+'
    MEMBER [Measures].[EntityKey] As '+@MDXEntityString+'.CurrentMember.Properties("KEY")
    MEMBER [Measures].[EntityName] As '+@MDXEntityString+'.CurrentMember.Properties("NAME")
  SELECT
  {
    [Measures].[DateTimeKey],
    [Measures].[KPIValue],
    [Measures].[EntityKey],
    [Measures].[EntityName]
  }ON COLUMNS
  ,
  {'
    +@MDXDateTimeKey+'} * {'+convert(nvarchar(max),@MDXEntityIdSet)+'
  } 
  dimension Properties MEMBER_CAPTION, MEMBER_KEY ON ROWS
  FROM 
  (
   '+@LocalTimeZoneId+'    
    FROM
    (
      SELECT
      {
        '+@MDXStartDate+':'+@MDXEndDate+'
      } ON COLUMNS     
      from [Measurements]
    )
  )'''+
')) ')

SET @SQLPart = 'Select  MQ.*, '+@MetaDataEntityObject+'.* '+IIF(@SelectStr<>'',','+@SelectStr,'')+' from MQ left join '+@MetaDataEntityObject+' on ''{''+CONVERT(nvarchar(max),'+@MetaDataEntityObject+'.Id)+''}'' = MQ.Schlüssel Order by MQ.Datum';

SET @sqlQuery = convert(nvarchar(max),@SQLMDXQuery + @MDXPart + @SQLPart);

I've read that it is possible to circumvent the 8000 character limit somehow, but the specifics elude me.

Any help here is appreciated.


Solution

  • I worked around the 8000 character limit by creating a second stored procedure that determines how many IDs can be passed at once to the first stored procedure without exceeding the 8000 character limit, calling it then multiple times and appending the resultset of each call to a temporary table.

    After the loop is finished I merely select * from the temporyr table.