Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

check rec exists in sql

Posted on 2013-01-09
2
Medium Priority
?
321 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 23

Accepted Solution

by:
Steve Wales earned 2000 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 Blockchain Technology?

Blockchain is a technology that underpins the success of Bitcoin and other digital currencies, but it has uses far beyond finance. Learn how blockchain works and why it is proving disruptive to other areas of IT.

Question has a verified solution.

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

This article shows gives you an overview on SQL Server 2016 row level security. You will also get to know the usages of row-level-security and how it works
In this article we will learn how to fix  “Cannot install SQL Server 2014 Service Pack 2: Unable to install windows installer msi file” error ?
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.

705 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