用程序结果填写临时表

时间:2018-04-11 18:22:05

标签: sql sql-server

我有一个名为#tempPrueba的tempTable:

+-----+----------+--------+
| ID  | FiltroID | Planta |
+-----+----------+--------+
|   1 |       12 | NULL   |
|   2 |        4 | NULL   |
|   3 |        8 | NULL   |
+-----+----------+--------+

你可以看到我的Planta有空值,我想通过执行存储过程填充它,当我执行这样的EXEC存储过程时:

EXEC [BSC].[ftNombreCortoBSC]
  @pe_BSCID = 12 --this equals to FiltroID of temporary table

它返回Planta值,因此我想用tempTable的每个FiltroID执行此存储过程,并将其添加到列Planta。我怎样才能实现它?此致

存储过程:

    USE [SIOD]
GO
/****** Object:  StoredProcedure [BSC].[ftNombreCortoBSC]    Script Date: 11/04/2018 11:39:16 a. m. ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [BSC].[ftNombreCortoBSC] (@pe_BSCID INT NULL, @splanta varchar (100) OUTPUT)

AS
BEGIN

--declare @splanta varchar(100) =''
set @splanta =''
declare @tablatemporal varchar(100) = ''
declare @campollave varchar(50) = ''
declare @camponombre varchar(50) = ''
declare @query nvarchar(max) = ''

Select @tablatemporal = d.sNombreFisico from bsc.Dimension d 
inner join bsc.ConfiguracionBalance cb on cb.DimensionID = d.ID 
WHERE cb.mdEstatusRegistro = 1 AND d.mdEstatusRegistro = 1 and cb.ID = @pe_BSCID


Select @camponombre = 'sNombre'+da.snombre from BSC.Dimension_Atributo da 
inner join bsc.ConfiguracionBalance cb on cb.DimensionID = da.DimensionID
where da.mdEstatusRegistro = 1 and da.sTipoAtributo = 'N'  and cb.ID = @pe_BSCID

Select @campollave = da.snombre from BSC.Dimension_Atributo da 
inner join bsc.ConfiguracionBalance cb on cb.DimensionID = da.DimensionID
where da.mdEstatusRegistro = 1 and da.mdEstatusRegistro = 1 and da.sTipoAtributo = 'L'  and cb.ID = @pe_BSCID

set @query = N'Select @splanta = '+@camponombre+' from '+@tablatemporal+' as tt  
inner join bsc.ConfiguracionBalance cb on cb.FiltroID = tt.key'+@campollave+' and cb.ID = 
' + convert(varchar(10),@pe_BSCID)

EXECUTE sp_executesql @query,N'@splanta varchar(50) output',@splanta output

SELECT @splanta

END

2 个答案:

答案 0 :(得分:1)

根据您的评论,这里有一个关于您如何使用游标执行此操作的掩码。我希望你的临时表只有4行,因为游标性能很糟糕。我只是无法弄清楚你在程序中做了什么,将它转换为基于集合的操作。话虽如此,这是一个例子......

--create a cursor to loop through your temp table
declare someCur cursor local fast_forward for
select id from #tempPrueba

--variables for cursor and holding output from proc
declare @id int
declare @procOutput varchar(256) --change this to the correct datatype and size

open someCur
fetch next from someCur into @id

 while @@FETCH_STATUS = 0
 begin

    --get the result from the proc for the first ID
    EXEC [BSC].[ftNombreCortoBSC] @id, @procOutput OUTPUT

    --update the temp table
    update #tempPrueba
    set Planta = @procOutput
    where ID = @id 

    --get the next ID
    fetch next from someCur into @id
 end

 close someCur
 deallocate someCur

答案 1 :(得分:0)

如果您的存储过程一次只能获取一个FiltroID值,那么使用它的唯一方法是使用游标遍历临时表中的FiltroID,获取与该FiltroID关联的Planta,然后更新该FiltroID表。