Search code examples
t-sqlsql-server-2008insertiontable-valued-parameters

Iterating through a TVP before inserting records?


I'd like some help writing the following sproc:

I have SQL Server 2008 sproc that accepts two integer values (@ID1 and @ID2) and a data table/TVP.

The TVP table contains several fields, ie. Title and Description.

I want to iterate through the TVP table and check if the Title or Description already exists in my data table, tbl_Items, where @ID1 = tbl_Items.ID1 and @ID2 = tbl_Items.ID2.

If neither exist then insert the values of @ID1 and ID2 and that TVP row into tbl_Items.

Thanks.


Solution

  • Something like this?

    INSERT INTO tbl_Items (ID1, ID2, Title, Description)
      SELECT
        @ID1, @ID2, TVP.Title, TVP.Description
      FROM
        @TVP AS TVP
      WHERE
        NOT EXISTS (SELECT * FROM tbl_Items AS I WHERE TVP.Title = I.Title AND TVP.Description = I.Description)