如何获得sp_executesql结果到一个变量?

我有一段动态SQL需要执行,然后我需要将结果存储到一个变量中。

我知道我可以使用sp_executesql,但找不到关于如何做到这一点的明确示例。

334784 次浏览

如果您有OUTPUT参数,您可以这样做

DECLARE @retval int
DECLARE @sSQL nvarchar(500);
DECLARE @ParmDefinition nvarchar(500);


DECLARE @tablename nvarchar(50)
SELECT @tablename = N'products'


SELECT @sSQL = N'SELECT @retvalOUT = MAX(ID) FROM ' + @tablename;
SET @ParmDefinition = N'@retvalOUT int OUTPUT';


EXEC sp_executesql @sSQL, @ParmDefinition, @retvalOUT=@retval OUTPUT;


SELECT @retval;

但如果没有,又不能修改SP:

-- Assuming that your SP return 1 value
create table #temptable (ID int null)
insert into #temptable exec mysp 'Value1', 'Value2'
select * from #temptable

不漂亮,但很好用。

DECLARE @vi INT
DECLARE @vQuery NVARCHAR(1000)


SET @vQuery = N'SELECT @vi= COUNT(*) FROM <TableName>'


EXEC SP_EXECUTESQL
@Query  = @vQuery
, @Params = N'@vi INT OUTPUT'
, @vi = @vi OUTPUT


SELECT @vi
DECLARE @tab AS TABLE (col1 VARCHAR(10), col2 varchar(10))
INSERT into @tab EXECUTE  sp_executesql N'
SELECT 1 AS col1, 2 AS col2
UNION ALL
SELECT 1 AS col1, 2 AS col2
UNION ALL
SELECT 1 AS col1, 2 AS col2'


SELECT * FROM @tab
Declare @variable int
Exec @variable = proc_name

返回值通常不用于“返回”结果,而是用于返回成功(0)或错误数(1-65K)。以上这些似乎都表明sp_executesql没有返回值,这是不正确的。Sp_executesql将返回0表示成功,返回任何其他数字表示失败。

在下面,@i将返回2727

DECLARE @s NVARCHAR(500)
DECLARE @i INT;
SET @s = 'USE [Blah]; UPDATE STATISTICS [dbo].[TableName] [NonExistantStatisticsName];';
EXEC @i = sys.sp_executesql @s
SELECT @i AS 'Blah'
SSMS将显示此内容 编号2727,11层,状态1,1号线 无法找到索引“NonExistantStaticsName”

这是很久以前的事了,所以不确定是否仍然需要,但是可以使用@@ROWCOUNT变量来查看前面的sql语句影响了多少行。

例如,当您构造一个动态Update语句并使用exec运行它时,这是很有用的。@@ROWCOUNT将显示有多少行被更新。

下面是定义

DECLARE @ValueTable TABLE
(
Value VARCHAR (100)
)


SELECT @sql = N'SELECT SRS_SizeSetDetails.'+@COLUMN_NAME+' FROM SRS_SizeSetDetails WHERE FSizeID = '''+@FSizeID+''' AND SRS_SizeSetID = '''+@SRS_SizeSetID+'''';


INSERT INTO @ValueTable
EXEC sp_executesql @sql;


SET @Value='';


SET @Value = (SELECT TOP 1  Value FROM @ValueTable)


DELETE FROM @ValueTable

如果你想返回一个以上的值,使用这个:

DECLARE @sqlstatement2      NVARCHAR(MAX);
DECLARE @retText            NVARCHAR(MAX);
DECLARE @ParmDefinition     NVARCHAR(MAX);
DECLARE @retIndex           INT = 0;


SELECT @sqlstatement = 'SELECT @retIndexOUT=column1 @retTextOUT=column2 FROM XXX WHERE bla bla';


SET @ParmDefinition = N'@retIndexOUT INT OUTPUT, @retTextOUT NVARCHAR(MAX) OUTPUT';


exec sp_executesql @sqlstatement, @ParmDefinition, @retIndexOUT=@retIndex OUTPUT, @retTextOUT=@retText OUTPUT;

返回值在@retIndex和@ retext中

这招对我很管用:

DECLARE @SQL NVARCHAR(4000)


DECLARE @tbl Table (
Id int,
Account varchar(50),
Amount int
)


-- Lots of code to Create my dynamic sql statement


insert into @tbl EXEC sp_executesql @SQL


select * from @tbl

你可以试试

DECLARE  @SqlStatement  NVARCHAR(MAX) = ''
,@result     XML
,@DatabaseName  VARCHAR(100)
,@SchemaName    VARCHAR(10)
,@ObjectName    VARCHAR(200);


SELECT   @DatabaseName = 'some database'
,@SchemaName   = 'some schema'
,@ObjectName   = 'some object (Table/View)'


SET @SqlStatement = '
SELECT @result = CONVERT(XML,
STUFF( ( SELECT *
FROM
(
SELECT TOP(100)
*
FROM ' + QUOTENAME(@DatabaseName) +'.'+ QUOTENAME(@SchemaName) +'.' + QUOTENAME(@ObjectName) + '
) AS A1
FOR XML PATH(''row''), ELEMENTS, ROOT(''recordset'')
), 1, 0, '''')
)
';


EXEC sp_executesql @SqlStatement,N'@result XML OUTPUT', @result = @result OUTPUT;


SELECT DISTINCT
QUOTENAME(r.value('fn:local-name(.)', 'VARCHAR(200)')) AS ColumnName
FROM @result.nodes('//recordset/*/*') AS records(r)
ORDER BY ColumnName