3 回答

TA貢獻(xiàn)1830條經(jīng)驗 獲得超9個贊
嘗試從存儲過程鏈中“冒泡”數(shù)據(jù)時,這是一個常見問題。SQL Server中的一個限制是您一次只能激活一個INSERT-EXEC。我建議查看“ 如何在存儲過程之間共享數(shù)據(jù)”,這是一篇非常詳盡的文章,介紹了解決此類問題的模式。
例如,一種變通方法是將Sp3轉(zhuǎn)換為表值函數(shù)。

TA貢獻(xiàn)1784條經(jīng)驗 獲得超2個贊
這是在SQL Server中執(zhí)行此操作的唯一“簡單”方法,而無需使用一些復(fù)雜的復(fù)雜創(chuàng)建函數(shù)或已執(zhí)行的sql字符串調(diào)用,這兩種方法都是很糟糕的解決方案:
創(chuàng)建一個臨時表
openrowset您的存儲過程數(shù)據(jù)
例:
INSERT INTO #YOUR_TEMP_TABLE
SELECT * FROM OPENROWSET ('SQLOLEDB','Server=(local);TRUSTED_CONNECTION=YES;','set fmtonly off EXEC [ServerName].dbo.[StoredProcedureName] 1,2,3')
注意:必須使用“ set fmtonly off”,并且不能在包含存儲過程參數(shù)的字符串或表名的openrowset調(diào)用中向其中添加動態(tài)sql。這就是為什么您必須使用臨時表而不是表變量的原因,這樣做會更好,因為它在大多數(shù)情況下會執(zhí)行臨時表。

TA貢獻(xiàn)1793條經(jīng)驗 獲得超6個贊
好的,在吉姆哈克(Jimhark)的鼓勵下,這是舊的單個哈希表方法的示例:-
CREATE PROCEDURE SP3 as
BEGIN
SELECT 1, 'Data1'
UNION ALL
SELECT 2, 'Data2'
END
go
CREATE PROCEDURE SP2 as
BEGIN
if exists (select * from tempdb.dbo.sysobjects o where o.xtype in ('U') and o.id = object_id(N'tempdb..#tmp1'))
INSERT INTO #tmp1
EXEC SP3
else
EXEC SP3
END
go
CREATE PROCEDURE SP1 as
BEGIN
EXEC SP2
END
GO
/*
--I want some data back from SP3
-- Just run the SP1
EXEC SP1
*/
/*
--I want some data back from SP3 into a table to do something useful
--Try run this - get an error - can't nest Execs
if exists (select * from tempdb.dbo.sysobjects o where o.xtype in ('U') and o.id = object_id(N'tempdb..#tmp1'))
DROP TABLE #tmp1
CREATE TABLE #tmp1 (ID INT, Data VARCHAR(20))
INSERT INTO #tmp1
EXEC SP1
*/
/*
--I want some data back from SP3 into a table to do something useful
--However, if we run this single hash temp table it is in scope anyway so
--no need for the exec insert
if exists (select * from tempdb.dbo.sysobjects o where o.xtype in ('U') and o.id = object_id(N'tempdb..#tmp1'))
DROP TABLE #tmp1
CREATE TABLE #tmp1 (ID INT, Data VARCHAR(20))
EXEC SP1
SELECT * FROM #tmp1
*/
- 3 回答
- 0 關(guān)注
- 1860 瀏覽
添加回答
舉報