Solved

check rec exists in sql

Posted on 2013-01-09
2
309 Views
Last Modified: 2013-01-12
How can I check if a record exists in sql? Something like this?

create procedure CheckRecExist
@id      int,
@accoutnumber varchar(24)
as

if exists(select * from myable where id ='myid' and accountnumber = 'xxxxxx')
select 1 else select 0
0
Comment
Question by:VBdotnet2005
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 22

Accepted Solution

by:
Steve Wales earned 500 total points
ID: 38761314
One way to do it would be via a user defined function

I had a table with students and scores in it:

CREATE FUNCTION CheckRecExists(@p1 char(20),@p2 decimal(9,2))
RETURNS bit
AS
BEGIN
   DECLARE @b bit
   if exists (select * from tab1 where student = @p1 and Score = @p2)
   set @b = 1 else set @b = 0
   RETURN @b
END
GO

Open in new window


When I did:

select dbo.CheckRecExists('Fred', 0.74)

(Note, for a function you do need to specify the schema name when you call it, otherwise you get an error about the function not existing).

I got back a 1 because the row existed.   Change to any other values, got a 0.

Your base syntax worked too:

if dbo.CheckRecExists('Fred', 0.74) = 1
  select 1 else select 0

(I'll leave it to others to point out any more efficient methods, I don't do a whole lot of development in general :))
0
 
LVL 21

Expert Comment

by:Alpesh Patel
ID: 38761778
select * from Table1 Where exists (Select * from Table2)
0

Featured Post

Percona Monitoring and Management and Grafana

Proactive monitoring is vital to a highly-available environment. We have a quick start guide on Experts Exchange for Grafana users.

Question has a verified solution.

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

The Delta outage: 650 cancelled flights, more than 1200 delayed flights, thousands of frustrated customers, tens of millions of dollars in damages – plus untold reputational damage to one of the world’s most trusted airlines. All due to a catastroph…
In part one, we reviewed the prerequisites required for installing SQL Server vNext. In this part we will explore how to install Microsoft's SQL Server on Ubuntu 16.04.
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
Viewers will learn how the fundamental information of how to create a table.

628 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