Reputation: 12369
UPDATE : This is what I did
-
set @dyn_sql = '
select
@UserName=UserName
from
(
select
E.ID as EmployeeID,
E.UserName as Username
from
Leaderboard K
inner join Employee E on K.EmployeeId = E.Id
inner join INFO KD on KD.EmployeeId=E.Id
where E.CompanyId=4
) as d1'
DECLARE @leaderboards TABLE
(
UserName varchar(50)
)
set @params='@Employee_Id int, @UserName varchar(200) OUTPUT'
INSERT INTO @leaderboards (UserName)
EXEC sp_executesql @dyn_sql, @params,@EmployeeId=@Employee_Id OUTPUT,@UserName = @User_Name OUTPUT
SELECT * from @leaderboards
But this is not returning records although if I see the query is right and returns records..
Hi all, I am executing a dynamic sql statement using sp_executesql and this is what I am doing currently -
EXEC sp_executesql @dyn_sql, @params,@EmployeeId=@Employee_Id OUTPUT,@UserName = @User_Name OUTPUT
SELECT @Employee_Id AS EmployeeId,@User_Name AS UserName
But the above only gets me single value when I am getting a list of records if I run the dynamic sql query individually.How can I store the list of values returned by execution of my dynamic sql ? and returns records..and returns records..But this
Upvotes: 1
Views: 6561
Reputation: 6015
Via a temp table.
[Update]
declare @sql nvarchar(max)
set @sql = '
select
E.ID as EmployeeID, --doesn't really matter how you name them, it's the order that matters
E.UserName as Username -- and this order should match the order of columns in the insert statement
from
Leaderboard K
inner join Employee E on K.EmployeeId = E.Id
inner join INFO KD on KD.EmployeeId=E.Id
where E.CompanyId=4
'
DECLARE @LeaderBoard TABLE
(
EmployeeId int,
UserName varchar(50)
)
INSERT INTO @LeaderBoard (EmployeeId, UserName)
exec sp_executesql @sql
select * from @LeaderBoard
--Hurray, we made it!
Upvotes: 1
Reputation: 453426
You can insert the results of EXEC sp_executesql
into a temp table or table variable.
DECLARE @t TABLE
(
a INT,
b INT
)
INSERT INTO @t (a,b)
EXEC sp_executesql N'SELECT 1, 2 UNION SELECT 3, 4 '
Or alternatively the dynamic SQL can access a temp table declared in the parent scope (but any temp table created in the dynamic SQL itself will be out of scope as soon as the execution finishes)
Upvotes: 1