Solved

Check if exists in stored procedure with table type

Posted on 2011-03-11
2
677 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 143

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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

There have been several questions about Large Transaction Log Files in SQL Server 2008, and how to get rid of them when disk space has become critical. This article will explain how to disable full recovery and implement simple recovery that carries…
Naughty Me. While I was changing the database name from DB1 to DB_PROD1 (yep it's not real database name ^v^), I changed the database name and notified my application fellows that I did it. They turn on the application, and everything is working. A …
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …

830 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