How to get sp_executesql result into a variable?

后端 未结 10 1436
刺人心
刺人心 2020-11-22 16:06

I have a piece of dynamic SQL I need to execute, I then need to store the result into a variable.

I know I can use sp_executesql but can\'t find clear e

10条回答
  •  难免孤独
    2020-11-22 17:04

    Return values are generally not used to "return" a result but to return success (0) or an error number (1-65K). The above all seem to indicate that sp_executesql does not return a value, which is not correct. sp_executesql will return 0 for success and any other number for failure.

    In the below, @i will return 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 will show this Msg 2727, Level 11, State 1, Line 1 Cannot find index 'NonExistantStaticsName'.

提交回复
热议问题