stevebot stevebot - 6 months ago 66
SQL Question

SQL Server: Execute nvarchar SQL statement and parametrize results without OUTPUT parameters

Is there a way to execute a SQL statement stored in nvarchar or ntext and parameterize the results of the executed SQL statement without using sp_executesql? E.g.

@SQL = 'SELECT name FROM db.dbo.employees WHERE income > 50000'

In this case, in a stored procedure, could I extract name without having to modify the query so I can use sp_executesql with an OUTPUT parameter defined for name?


What in the world is preventing you from using SP_EXECUTESQL? Is this a strip from Dilbert?

Anyway, if you used an output parameter with that specific query, it'll most likely return a single (random) value from all employees whose income exceed 50,000. Here's an example showing how to return an entire result to the caller of a dynamic SQL statement.

The key here is INSERT.. EXEC

create table dbo.employees (
  name varchar(10),
  income int);
insert employees values
 ('john', 10000),
 ('joe' , 20000),
 ('joey', 40000),
 ('bob' , 70000),
 ('tim' , 100000);

declare @SQL nvarchar(max) =
    'SELECT name FROM dbo.employees WHERE income > 50000';

declare @names table (name varchar(20));
insert @names
select * from @names;