计算存储过程结果中的行数,然后将结果插入 table

Count # of Rows in Stored Procedure Result, then Insert result into table

我有一个 SSIS 包,它将首先 运行 我的 sp_doSomething。此存储过程将从几个不同的表中 select 数据并将它们连接起来以便可能存储到 dbo.someTable 中。但我只想要如果 select 是 > 1 行 selected 数据。

然后我想有一个优先限制来查看我的存储过程返回的行数。

如果我的行数 > 1,那么我想获取存储过程的结果并将它们插入到我的一个表中。

否则,我会记录 error/send 一封电子邮件,或其他任何内容。

我真的不想 运行 这个存储过程不止一次,但这是我能想到的唯一方法(运行 它,计算行数。然后, 运行 再次插入结果。

我是一个完整的 TSQL/SSIS 新手。所以如果这个问题很微不足道,我很抱歉。 我无法在任何地方找到好的答案。

#temp table 适合你吗?

IF OBJECT_ID('tempdb..#Holder') IS NOT NULL
begin
    drop table #Holder
end


CREATE TABLE #Holder
(ID INT )




declare @MyRowCount int
declare @MyTotalCount int = 0

/* simulate your insert, you would read from your real table(s) here */
INSERT INTO #HOLDER (ID) 
select 1 union all select 2 union all select 3 union all select 4

Select @MyRowCount = @@ROWCOUNT, @MyTotalCount = @MyTotalCount + @MyRowCount
Select 'TheMagicValue1' = @MyRowCount, 'TheMagicTotal' = @MyTotalCount

INSERT INTO #HOLDER (ID) 
select 5 union all select 6 union all select 7 union all select 8

/* you will note that I am NOT doing a count(*) here... which is another strain on the procedure */    

Select @MyRowCount = @@ROWCOUNT, @MyTotalCount = @MyTotalCount + @MyRowCount
Select 'TheMagicValue1' = @MyRowCount, 'TheMagicTotal' = @MyTotalCount

/* Optional index if needed */
CREATE INDEX IDX_TempHolder_ID ON #Holder (ID)
/* CREATE CLUSTERED INDEX IDX_TempHolder_ID ON #Holder (ID) */    


if @MyTotalCount > 0
BEGIN
    Select 'Put your INSERT statement here'
END


/* this will return the data to the report */
Select ID from #HOLDER


IF OBJECT_ID('tempdb..#Holder') IS NOT NULL
begin
    drop table #Holder
end

在存储过程中,将结果写入#Temp。然后Select Count(*) 从#Temp,变成一个变量。

Select @intRows = Count(*) from myTempResults

然后计算@intRows 的值。

If @intRows > 1 BEGIN

Insert Into dbo.SomeTable 
Select * from #Temp 

End

你可以试试这个

declare @tableVar table(col1 varchar(100))
declare @Counter int
insert into @tableVar(col1)  exec CompanyNames

set @Counter = (select count(*) from @tableVar)
insert into Anytable(col) Values (@counter)

创建一个包范围为 Int32 且名称为 rowcount 的变量。

数据流

控制流程