Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 330
  • Last Modified:

check rec exists in sql

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
VBdotnet2005
Asked:
VBdotnet2005
1 Solution
 
Steve WalesSenior Database AdministratorCommented:
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
 
Alpesh PatelAssistant ConsultantCommented:
select * from Table1 Where exists (Select * from Table2)
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now