Solved

check rec exists in sql

Posted on 2013-01-09
2
280 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
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

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Question has a verified solution.

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

Suggested Solutions

Everyone has problem when going to load data into Data warehouse (EDW). They all need to confirm that data quality is good but they don't no how to proceed. Microsoft has provided new task within SSIS 2008 called "Data Profiler Task". It solve th…
I have a large data set and a SSIS package. How can I load this file in multi threading?
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

809 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