sql从select语句返回数据并同时插入表变量

时间:2012-11-08 11:54:48

标签: sql-server-2008 tsql select

declare @RelevantMachines Table (MachineId int)

Select MachineId, ClusterId, MachineGuid, MachineName, RegisteredDate, MachineDetail, LastServiceCall, MachineType as MachineTypeId, ProductSetId
From PatchHub.Machine
Where ClusterId = @ClusterId

我希望能够将select语句作为结果集返回,同时使用所有返回的行MachineId值填充表变量,这是在sql server 2008中。如何在不运行的情况下实现此目的选择语句两次?

1 个答案:

答案 0 :(得分:1)

我不相信你可以在一个SELECT中做到这一点,我认为下一个最好的事情是这样的:

declare @result table (
MachineId int, 
ClusterId int, 
MachineGuid guid, 
MachineName varchar(100), 
RegisteredDate datetime, 
MachineDetail varchar(1000), 
LastServiceCall int, 
MachineType int, 
ProductSetId int)

Select MachineId, ClusterId, MachineGuid, MachineName, RegisteredDate, MachineDetail, LastServiceCall, MachineType as MachineTypeId, ProductSetId
into @result
From PatchHub.Machine
Where ClusterId = @ClusterId

select * from @result

/* use @result table */