title: insert text into table conditional on values returned from stored procedures (and a select statement)
body: <p>My goal is to update a table with a string "finished" and some static values (in the other columns in the table), based on a select statement and conditional that the output from the select statements fulfil certain conditions. These conditions are that the output from around 18 stored procedures are returned with a value=0. </p>
  
  <p>Each stored procedure returns some value ("<code>Number_of</code>") for each unit  ("<code>EnhetsId</code>"), ranging from 0 to infinity. The stored procedures first calls a database ('<code>GR_PS09_1</code>') and then a unique unit based on its unit ID ('<code>EnhetsId</code>').</p>
  
  <p>So first I have a select statement, that given a certain condition gives me an output of a number of units. Then, if these units fulfil the condition that the SP returns the value 0 for each of the units, I want to insert into a temp-table the "qualified" unit ID (<code>EnhetsId</code>), some static values and the string "finished".</p>
  
  <p>My code so far, with <a href="https://stackoverflow.com/a/20019594/2589202">help from @MrReband</a>:</p>
  
  <pre><code>declare @temp2 table (
  EnhetsId varchar(50), 
  TjanstId Int, 
  Tabell varchar(50),
  Kommentar ntext,
  Uppdaterad datetime 
  );
  
  
  WITH ENHET_CTE AS 
  (
  SELECT A.[EnhetsId]
  FROM [StatistikinlamningDataSKL].[dbo].[StatusHistorik] A
  inner join (
           select [EnhetsId], max(SenastUppdaterad) as SenastDatum
           from [StatistikinlamningDataSKL].[dbo].[StatusHistorik]
           group by [EnhetsId]
           ) B
  on A.[EnhetsId] = B.[EnhetsId] and A.[SenastUppdaterad] = B.SenastDatum
  WHERE [NyStatus] = 4
  ),        
   /* this code below is the one I am trying to solve */
  SP_01 AS
  (
  set @enhet = (select exec StatistikinlamningDataSKL.dbo.SKL_admin_KN_aform 'GR_PS09_1', '''EnhetsId'''
  where 'Number_of' = 0)
  
  ), 
  
  /*add more stored procedures*/
  
  insert into @temp2 
  (EnhetsId, TjanstId, Tabell, Kommentar, Uppdaterad) 
  SELECT 
  EnhetsId, 1, 'GR_PS09_1', 'finished', getdate() 
  from ENHET_CTE;
  </code></pre>
  
  <p>Does anyone have some input on how to proceed with this code?</p>