2012-11-08 39 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正在尋找的內容,您應該將其寫爲答案。 –