poshan
poshan

Reputation: 3287

How to call a stored procedure to populate one table from another in SQL Server?

I am still new to SQL, so doing it by learning. I would like to populate a table using stored procedure. My question is how do I call the procedure so that it gets executed and the table gets populated. So far I have done this.

ALTER proc [dbo].[MytestTableLoad]
   @ID int,
   @FirstName varchar,
As
Begin
   Set nocount on;

   merge dbo.MytestTable2 as target
   using (select @ID, @FirstName,@LastName) as source (Id, FirstName, LastName)
   on (target.Id=source.Id)
   when not matched then
     Insert   (Id, FirstName, LastName)
     values (@Id, @FirstName,@LastName)
   ;
END    

Upvotes: 0

Views: 1815

Answers (2)

Nick.Mc
Nick.Mc

Reputation: 19184

"how do I call the procedure so that it gets executed and the table gets populated."

Like this:

EXEC MytestTableLoad 1,'Bob'

Upvotes: 0

Dan Bracuk
Dan Bracuk

Reputation: 20804

An easier syntax would be;

insert into table2
(field1, field2, etc)
select field1, field2, etc
from SomeOtherTables
where not exists
(subquery to check for records you don't want.)

Upvotes: 1

Related Questions