Solved

check rec exists in sql

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

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Suggested Solutions

Let's review the features of new SQL Server 2012 (Denali CTP3). It listed as below: PERCENT_RANK(): PERCENT_RANK() function will returns the percentage value of rank of the values among its group. PERCENT_RANK() function value always in be…
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…
This video shows, step by step, how to configure Oracle Heterogeneous Services via the Generic Gateway Agent in order to make a connection from an Oracle session and access a remote SQL Server database table.
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.

708 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

16 Experts available now in Live!

Get 1:1 Help Now