我正在尝试使用动态SQL在远程服务器上执行一些逻辑,但是当我设置动态SQL并尝试调用它时,没有任何反应。如果我调用执行而不使执行动态,它可以毫无问题地工作。
不确定在传递输出值时是否允许我尝试做的事情,但我想我会看看是否有人有任何想法
DECLARE @sqlserver NVARCHAR(MAX) = ''
DECLARE @DBName NVARCHAR(MAX) = ''
DECLARE @parms NVARCHAR(MAX) = N'@output INT OUT', @output INT, @sql NVARCHAR(MAX) = '
;WITH DuplicateStatusCodes AS (
SELECT CodeTypeID FROM EDDSDBO.Code WHERE Name = ''Master'' OR Name = ''Unique'' OR Name = ''Duplicate''
)
SELECT ROW_NUMBER() OVER (ORDER BY CodeTypeID) RN, CodeTypeID INTO #temp
FROM DuplicateStatusCodes
GROUP BY CodeTypeID
HAVING COUNT(CodeTypeID) = 3
DECLARE @count INT = (SELECT COUNT(1) FROM #temp)
DECLARE @ctr INT = 1;
IF @count > 0
BEGIN
WHILE @ctr <= @count BEGIN
DECLARE @parms NVARCHAR(MAX) = N''@inneroutput INT OUT'';
DECLARE @inneroutput INT
DECLARE @codeartifact INT = (SELECT CodeTypeID FROM #temp WHERE RN <= 1 * @ctr and RN > 1 * (@ctr - 1))
DECLARE @duplicatestatuscheck NVARCHAR(MAX) = ''SELECT @inneroutput = COUNT(1) FROM eddsdbo.codeartifact_''+CAST(@codeartifact AS VARCHAR)+''''
EXEC sys.sp_executesql @duplicatestatuscheck, @parms, @inneroutput OUT
SELECT @output = @inneroutput
IF @inneroutput > 0
BREAK;
SET @ctr = @ctr + 1;
END
END
ELSE
BEGIN
SELECT @output = ''0''
END
'
DECLARE @linksql NVARCHAR(MAX) = '
DECLARE @sql NVARCHAR(MAX)
DECLARE @parms NVARCHAR(MAX) = N''@output INT OUT''
EXEC '+QUOTENAME(@sqlserver)+'.'+QUOTENAME(@DBName)+'.sys.sp_executesql @sql, @parms, @output = @output OUT'
--This does not work
EXEC sp_executesql @linksql, @parms, @output = @output
PRINT @output
--This works fine
EXEC [RemoteServerName].[DatabaseName].sys.sp_executesql @sql, @parms, @output = @output OUT ```
Appreciate any help
你需要使用 OPENROWSET。像这样:
DECLARE @ServerName VARCHAR(255) = '...'
,@DatabaseName VARCHAR(255) = '...'
,@Pwd VARCHAR(255) = '...'
,@UID VARCHAR(255) = '...'
,@Name VARCHAR(255) = 'Master'
DECLARE @connect varchar(max) = '''Server=' + @ServerName + ';database=' + @DatabaseName + ';Uid=' + @UID + ';Pwd=' + @Pwd + ';'''
declare @sqlstring varchar(max) = 'SET ANSI_NULLS OFF; SET ANSI_WARNINGS OFF;
SELECT CodeTypeID FROM EDDSDBO.Code WHERE Name = ''''' + @Name + ''''' '
declare @TheExecutableStr varchar(max) = '
SELECT *
FROM OPENROWSET(''SQLNCLI'', ' + @connect + ',
''' + @sqlstring + ''')'
SELECT @TheExecutableStr
--EXEC(@TheExecutableStr)
请注意,您必须非常勤奋地计算单引号,因此选择@TheExecutableStr。它用于调试目的。您可以查看要执行的查询,并在取消注释最后一个语句之前实际复制/粘贴和执行。 希望对您有所帮助。
刚刚注意到,您在sys.sp_executesql内sys.sp_executesql可能有问题。 您可能需要找到一种方法来重构代码。