Dynamic sql with output parameter in SQL Server

The following query outputs the count of customers belong to code ’65’ to a parameter using a dynamic query.

declare @query nvarchar(1000), @j int, @parmDefinition nvarchar(500);
set @query = N’select @i = count(*) from customer where code = ”65” group by code’
print @query
set @parmDefinition = N’@i int OUTPUT’;
execute sp_executesql @query,@parmDefinition,@i = @j output
select @j

Advertisements