title: How to insert values into table from stored procedure inputs as well as temp table
body: <p>I have a stored procedure like this:</p>
  
  <pre><code>create procedure spname
      @ID varchar,
      @name varchar,
      @R xml
  AS
  BEGIN
      -- Getting values XML
      create table #Table
      (
         country varchar,
         status varchar
      )
  </code></pre>
  
  <p>I have to insert the values into a table based on the condition that if ID, Name which are from stored procedure input and country (from temp table) doesn't exists, then insert. I don't know exact syntax os how to join all these. However I tried below, but I reckon its wrong, I think I must some some looping technique like cursor? </p>
  
  <pre><code>DECLARE @Country VARCHAR;
  
  SELECT @Country = C.Country 
  FROM #Table C
  
  INSERT INTO MyTable(Id, Name, Country)
  VALUES (@Id, @Name, @Country)
  FROM 
      WHERE NOT EXISTS (SELECT 1 FROM MyTable mT
                        WHERE ID = @Id
                          AND Name = @Name
                          AND mt.country = C.country)
  </code></pre>
  
  <p>I am thinking there is wrong syntax in values as well as it will not serve my purpose as temp table contains a lot of values</p>
  
  <p>I came up with a solution this way using cursor:</p>
  
  <pre><code>  DECLARE @country VARCHAR
  
      DECLARE CountryCur CURSOR FOR 
          SELECT Country FROM #Temp
  
      OPEN CountryCur 
  
      FETCH NEXT FROM CountryCur INTO @Country
  
      WHILE @@FETCH_STATUS = 0 
      BEGIN
          INSERT INTO MyTable(Id, Name, Country)
          VALUES (@id, @name, @Country)
          WHERE NOT IN (SELECT 1 FROM MyTable mT
                        WHERE mT.Id = @Id
                          AND mT.name = @name
                          AND mT.country = @Country)
  
          FETCH NEXT FROM CountryCur INTO @Country
          CLOSE CountryCur 
          DEALLOCATE CountryCur 
  </code></pre>
  
  <p>However, it shows syntax error near where. Don't know whats wrong. </p>