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

时间:2015-08-12 19:35:00

标签: sql-server tsql stored-procedures ssis

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

我希望有一个优先约束,查看我的存储过程返回的行数。

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

否则,我会记录错误/发送电子邮件,或其他任何内容。

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

我是一个完整的TSQL / SSIS newb。如果这个问题很简单,我很抱歉。 我无法在任何地方找到一个好的答案。

A little visualization never hurt

4 个答案:

答案 0 :(得分:2)

使用类型为Int32的包范围创建一个变量,并命名为rowcount。

数据流

enter image description here

控制流程

enter image description here

答案 1 :(得分:0)

#temp表会为你工作吗?

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

答案 2 :(得分:0)

在Stored Proc中,将结果写入#Temp。然后从#Temp中选择Count(*)到变量。

Select @intRows = Count(*) from myTempResults

然后评估@intRows的值。

If @intRows > 1 BEGIN

Insert Into dbo.SomeTable 
Select * from #Temp 

End

答案 3 :(得分:0)

你可以试试这个

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)