Solved

Check if exists in stored procedure with table type

Posted on 2011-03-11
2
667 Views
Last Modified: 2012-05-11
Hi,

I have a stored procedure that inserts from a table type like the code below:

How can I check if xxxx already exists and instead Update that row?

I use this for inserting messages through BizTalk.

Best Regards
ALTER PROCEDURE [dbo].[InsertStuff]
(
	@parStuff AS dbo.StuffTableType READONLY
)
AS
SET NOCOUNT ON
BEGIN
DECLARE 
@id int

INSERT INTO dbo.Stuff(
	[xxx],[xxxx],[xxxxx]   
SELECT [xxx],[xxxx],[xxxxx]
FROM @parStuff;

Open in new window

0
Comment
Question by:mattegol
2 Comments
 
LVL 142

Accepted Solution

by:
Guy Hengel [angelIII / a3] earned 500 total points
ID: 35108031
you have to do that based on the key field(s):
 ALTER PROCEDURE [dbo].[InsertStuff] ( @parStuff AS dbo.StuffTableType READONLY ) AS SET NOCOUNT ON BEGIN -- to update existing rows, xxx is the primary key field UPDATE s SET xxxx = p.xxxx , xxxxx = p.xxxxx FROM dbo.Stuff s JOIN @parStuff p ON p.xxx = s.xxx INSERT INTO dbo.Stuff ( [xxx],[xxxx],[xxxxx] ) SELECT [xxx],[xxxx],[xxxxx] FROM @parStuff p LEFT JOIN dbo.Stuff s --- LEFT join plus below on s.xxx = p.xxx WHERE s.xxx IS NULL -- left join plus this will make you will only insert "new" rows here 

Open in new window



0
 
LVL 21

Expert Comment

by:Alpesh Patel
ID: 35108343
If not exists (select 1 from dbo.Stuff    where field =   [xxx] )
INSERT INTO dbo.Stuff(
        [xxx],[xxxx],[xxxxx]  
SELECT [xxx],[xxxx],[xxxxx]
FROM @parStuff;
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Suggested Solutions

Occasionally there is a need to clean table columns, especially if you have inherited legacy data. There are obviously many ways to accomplish that, including elaborate UPDATE queries with anywhere from one to numerous REPLACE functions (even within…
How to leverage one TLS certificate to encrypt Microsoft SQL traffic and Remote Desktop Services, versus creating multiple tickets for the same server.
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now