⌘BABAKOV.NET Let's code!
100% [dark] [ru]

Executing a Dynamically Created Script with Returning a Parameter SP_EXECUTESQL - MSSQL

Example of returning a parameter when executing a dynamically created query.

May be useful in cases where you need to return parameters for further processing in a script, for example, a procedure.


We will use this for sp_executesql

DECLARE @eventCount as int = 0; -- Наш возвращаемый параметр
DECLARE @sqlString AS NVARCHAR(500); -- Динамически сгенерированный SQL скрипт
DECLARE @parmDefinition AS NVARCHAR(500); -- Набор параметров для обмена

DECLARE @actualDate as date = \'2000-08-24\';
DECLARE @tableName as varchar(max) = \'sys.tables\';

SET @parmDefinition = N\'@outputCount int OUTPUT,@DateSend date\';
SET @sqlString = N\'select @outputCount = count(1) from \'+@tableName+\' where create_date>@dateSend;\';

EXEC sp_executesql
    @stmt = @sqlString, -- Динамически созданный запрос
    @params = @parmDefinition, -- Описание передаваемых параметров (как в запрос так и обратно)
    @dateSend = @actualDate, -- Принимаемый параметр
    @outputCount = @eventCount OUTPUT; -- Возвращаемый параметр

SELECT @eventCount AS CountEvents;

Comments (0)

No comments yet.

Leave a comment
Comment
Images (up to 5 MB)
Your comment will appear after moderation.