如何存储从sp_executesql返回的多个值或列表值?

时间:2010-09-08 22:10:03

标签: sql-server sql-server-2008 dynamic-sql sp-executesql

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


大家好,我正在使用sp_executesql执行动态sql语句,这就是我目前正在做的事情 -

EXEC sp_executesql @dyn_sql, @params,@EmployeeId=@Employee_Id OUTPUT,@UserName = @User_Name OUTPUT

SELECT @Employee_Id AS EmployeeId,@User_Name AS UserName

但是如果我单独运行动态sql查询,那么当我获取记录列表时,上面只会得到单个值。如何存储执行动态sql返回的值列表? 并返回记录..并返回记录。但是这个

2 个答案:

答案 0 :(得分:1)

通过临时表。

<强> [更新]

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!

答案 1 :(得分:1)

您可以将EXEC sp_executesql的结果插入到临时表或表变量中。

DECLARE  @t TABLE
(
a INT,
b INT
)
INSERT INTO @t (a,b)
EXEC sp_executesql N'SELECT 1, 2 UNION SELECT 3, 4 '

或者,动态SQL可以访问在父作用域中声明的临时表(但是一旦执行完成,动态SQL本身创建的任何临时表都将超出范围)