将使用exec的存储过程转换为将表填充到标量值函数

时间:2016-11-23 21:20:26

标签: sql-server function stored-procedures sql-server-2012 user-defined-functions

我有这个存储过程:

ALTER procedure [dbo].[sp_checker2] 
    (@Item varchar(70), @location varchar(8))      
as      
    declare @Query varchar(2000)      
    set @location = 'XXX909'   

    declare @Table Table (Qty int)      
    set @Query = 'select TOP 1 * from openquery(xxxx,''SELECT NVL(b.t$st,0) from server.XXXXXID0001 a left join  
server.XXXXXID0002 b on a.t$item = b.t$item where b.t$cloc = '''''+ @location + ''''' and trim(a.t$item)='''''+ @Item + ''''''')'      

   insert into @Table exec (@Query)      
   if not exists (select * from @Table )
  begin
     set @Query = 'select TOP 1 * from openquery(xxxx,''SELECT NVL(b.t$st,0) from server.XXXXXID0001 a 
     left join server.XXXXXID0002 b on a.t$item = b.t$item where trim(a.t$item) = '''''+ @Item + ''''''' )'    

    insert into @Table exec (@Query)
    end
    select * from @Table

问题是我正在寻找这样的查询SELECT

SELECT 
    column1, column2, column3, column4, 
    (EXEC [dbo].[sp_checker2] 'param1=value of column3', 'param2=another value') AS column5 
FROM 
    table 
WHERE 
    column1 = 'data1' 
    AND column2 = 'data2' 
ORDER BY 
    column3

我知道在SQL Server的SELECT语句中执行存储过程是不可能的,而我的替代方法是将存储过程转换为函数,但在存储过程中我有{{{ 1}}将数据插入表变量。有没有办法将这个存储过程转换为函数?

P.S。我只在变量表中保存了一行,即:如果项目存在则保存其库存:“6500”

1 个答案:

答案 0 :(得分:0)

很难。在函数中,无法执行动态SQL。我认为只有在WHERE标准发生转变时才有可能。您将能够更好地评估这对性能产生的影响。

CREATE FUNCTION [dbo].[f_checker2] (@item     varchar(70), 
                                    @location varchar(8))
  RETURNS @result TABLE (
                    Qty int
                  )
AS
BEGIN
  INSERT
    INTO @result
         select TOP(1) qty
           from openquery(xxxx, 'SELECT NVL(b.t$st,0)  AS qty,
                                        b.t$cloc       AS location,
                                        trim(a.t$item) AS item
                                   from server.XXXXXID0001 a 
                                        left join server.XXXXXID0002 b 
                                               on a.t$item = b.t$item')
   where location =  @location
     and item     =  @item

  if not exists (select * from @result)
    INSERT
      INTO @result
           select TOP(1) qty 
             from openquery(xxxx, 'SELECT NVL(b.t$st,0)  AS qty,
                                          b.t$cloc       AS location,
                                          trim(a.t$item) AS item
                                     from server.XXXXXID0001 a 
                                          left join server.XXXXXID0002 b 
                                                 on a.t$item = b.t$item')
     where item =  @item

  RETURN
END

GO