How to get sp_executesql result into a variable?

2019-01-01 00:40发布

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 examples around about how to do this.

9条回答
ら面具成の殇う
2楼-- · 2019-01-01 01:08
DECLARE @tab AS TABLE (col VARCHAR(10), colu2 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
查看更多
人间绝色
3楼-- · 2019-01-01 01:09

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'.

查看更多
宁负流年不负卿
4楼-- · 2019-01-01 01:12

Declare @variable int

Exec @variable = proc_name

查看更多
不流泪的眼
5楼-- · 2019-01-01 01:17

This worked for me:

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
查看更多
低头抚发
6楼-- · 2019-01-01 01:21

If you want to return more than 1 value use this:

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;

returned values are in @retIndex and @retText

查看更多
姐姐魅力值爆表
7楼-- · 2019-01-01 01:22

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
查看更多
登录 后发表回答