2012-11-08 38 views
0
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中。你怎么能实现这个没有两次运行select语句?SQL从select语句返回数据并同时插入表变量

+0

有没有什么不能运行两次特殊原因,或如果可能的话,这只是你不想做的事情? – Jasper

+0

运行两次需要两倍的时间,我的应用程序需要返回的集合,其余的存储过程将从存储的machineId的集合中获益,而不必再次执行此选择语句 – 0xor1

+0

您可以自动插入&select与OUTPUT,但你需要将所有的列添加到您的表变量,如果你不想你可以选择和插入变量中的ID然后选择从内部加入到基础表 –

回答

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 */ 
+0

你这就是我但它并没有改善我希望的表现,啊,从来没有想过,多亏了谢谢 – 0xor1

+0

如果表格变量与select有相同的列,你可以一次完成; 'insert @result output inserted。* select xxx from xxx' –

+0

@AlexK。我没有想到这一点。您的评论可能是OP正在寻找的内容,您应该将其写为答案。 –