查询执行动态查询的存储过程。错误链接服务器表示对象没有列

时间:2014-10-29 13:54:34

标签: sql-server sql-server-2008 tsql stored-procedures

我有一个动态创建数据透视查询的存储过程。

该过程有效并返回正确的数据。

现在我需要在报表系统中显示此数据,该系统只能从表或视图中提取。由于您无法在视图中创建动态查询,因此我尝试使用openquery进行选择。

示例'

  

从OpenQuery中选择*([MyServername],' Exec   Instance.Schema.StoredProcedure&#39)

我收到错误

  

"链接服务器表示该对象没有列"。

我认为这是因为第一个使用列名填充变量的select语句。

程序代码

ALTER PROCEDURE [dbo].[FuelCombustorMatrix]


AS
BEGIN
-- Use Master

SET NOCOUNT ON

Declare @cols nvarchar(2000),
        @Tcols nvarchar(2000),
        @Sql nvarchar (max)

select @cols = stuff ((
                        Select distinct '], ['+ModelName + '  ' + CombustorName
                            from CombustorFuel cf
                            join Model m on cf.modelid = m.modelid
                            join Combustors cb on cf.CombustorID = cb.CombustorID
                            where cf.CombustorID > 0
                            for XML Path('')
                        ),1,2,'')+']'

Set @Tcols = replace(@Cols, ']', '] int')
--Print @Tcols          
--Print @Cols

Set @Sql = 'Select GasLiquid, FuelType, '+ @Cols +'
from 
    (
    Select GasLiquid, FuelType, ModelName+ ''  '' +CombustorName ModelCombustor, CombFuelStatus+''- ''+CombFuelNote CombFuelStatusNote
        from Frames f
        join Family fa on f.Frameid = fa.frameid
        join Model m on fa.FamilyID = m.FamilyID
        join CombustorFuel cf on m.Modelid = cf.modelid
        Join Combustors c on cf.CombustorId = c.CombustorID
        join FuelTypes ft on cf.FuelTypeID = ft.FuelTypeID
        where cf.CombustorFuelID > 0
          and CombustorName <> ''''
    ) up
Pivot 
    (max(CombFuelStatusNote) for ModelCombustor in ('+ @Cols +')) as pvt
order by FuelType'

exec (@Sql)

END

0 个答案:

没有答案