不重复。这里的问题是它有不同的结构。我对可以改变的东西和我能做的事情有一些限制。在这里我有一个确切的例子,其他门票不是。 OPENROWSET也不能应用,因为test1循环遍历所有dbs(using EXEC sp_MSforeachdb @sql)
。我无法使用它,因为在OPENROWSET中你必须指定从哪个db运行过程
假设我有这两个SP:
create procedure test1
@ProcName varchar(155)
as
begin
if OBJECT_ID('tempdb..#testt') is not null drop table #testt
create table #testt1(a int, b int)
insert #testt1
exec @ProcName
select * from #testt1
end
create procedure test2
as
begin
declare @sql varchar(155)
if OBJECT_ID('tempdb..#testt2') is not null drop table #testt2
create table #testt2(a int, b int)
select @sql = 'select 1 as a,2 as b'
insert #testt2
exec (@sql)
select * from #testt2
end
当我运行exec test1 @ProcName = 'Test2'
时,它会返回错误:
无法嵌套INSERT EXEC语句。
这里的问题是我无法在insert exec
中停止使用test2
。 test1应该将@ProcName作为变量
解决此问题的最简单方法是什么?
答案 0 :(得分:0)
尝试使用表变量替换第二个过程中的临时表,然后使用OPENQUERY(如http://www.sommarskog.se/share_data.html中所述),如下所示:
CREATE DATABASE Database1
CREATE DATABASE Database2
GO
DECLARE @ProcedureTest2 NVARCHAR(MAX)
SET @ProcedureTest2='create procedure test2
as
begin
SET NOCOUNT ON
declare @sql varchar(155)
DECLARE @testt2 TABLE (a int, b int)
select @sql = ''select 1 as a,2 as b''
insert @testt2
exec (@sql)
select * from @testt2
end'
DECLARE @SQL NVARCHAR(MAX)
SET @SQL='USE Database1 EXEC('''+REPLACE(@ProcedureTest2,'''','''''')+''')'
EXEC(@SQL)
SET @SQL='USE Database2 EXEC('''+REPLACE(@ProcedureTest2,'''','''''')+''')'
EXEC(@SQL)
GO
EXEC sp_addlinkedserver @server = 'LOCALSERVER', @srvproduct = '', @provider = 'SQLOLEDB', @datasrc = @@servername
GO
CREATE procedure test1
@ProcName varchar(155)
as
begin
if OBJECT_ID('tempdb..#testt1') is not null drop table #testt1
create table #testt1(a int, b int)
DECLARE @Databases TABLE (DBName sysname PRIMARY KEY)
INSERT INTO @Databases VALUES ('Database1')
INSERT INTO @Databases VALUES ('Database2')
DECLARE Databases CURSOR LOCAL READ_ONLY FOR
SELECT * FROM @Databases d
DECLARE @DBName sysname
OPEN Databases
WHILE 1=1 BEGIN
FETCH NEXT FROM Databases INTO @DBName
IF @@FETCH_STATUS<>0 BREAK
DECLARE @SQL1 NVARCHAR(500), @SQL2 NVARCHAR(1000)
SET @SQL1='EXEC '+QUOTENAME(@DBName)+'.dbo.'+QUOTENAME(@ProcName)
SET @SQL2='SELECT * FROM OPENQUERY(LOCALSERVER, '+QUOTENAME(@SQL1,'''')+')'
PRINT @SQL2
INSERT INTO #testt1
EXEC (@SQL2)
END
CLOSE Databases
DEALLOCATE Databases
select * from #testt1
end
GO
--EXEC [Database1].dbo.[test2]
--SELECT * FROM OPENQUERY(LOCALSERVER, 'EXEC [Database1].dbo.[test2]')
EXEC dbo.test1 'test2'
GO
EXEC sp_dropserver 'LOCALSERVER'
DROP PROCEDURE test1
DROP DATABASE Database1
DROP DATABASE Database2
答案 1 :(得分:0)
将insert
语句放在test2过程中解决了问题