Daniel Robinson
Daniel Robinson

Reputation: 14858

sql return data from select statement and insert to table variable at the same time

declare @RelevantMachines Table (MachineId int)

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

I would like to be able to return the select statement as a result set whilst at the same time populating the table variable with all of the returned rows MachineId values, this is in sql server 2008. How could you achieve this without running the select statement twice?

Upvotes: 0

Views: 656

Answers (1)

Ivan Golović
Ivan Golović

Reputation: 8832

I don't believe you can do it in a single SELECT, I think the next best thing would be something like this:

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

Upvotes: 1

Related Questions