Friday, February 24, 2012

Exist Return Values

Hi ,
I like to use a variable to store the return values (True / False) of the
exists statement. How can I do that ? I unable to do that from my query show
below
declare @.bln
set @.bnl = Select Distinct Cust_Id,Cust_Name From Temp_Customer
Where Not Exists
(Select Cust_Id,Cust_Name From MyDb.dbo.Customer
Where MyDb.dbo.Customer .Cust_Id = Temp_Customer.Cust_Id)
Please Help ..
Travis Tan
On Sun, 24 Jul 2005 22:00:01 -0700, Travis wrote:

>Hi ,
> I like to use a variable to store the return values (True / False) of the
>exists statement. How can I do that ? I unable to do that from my query show
>below
>declare @.bln
>set @.bnl = Select Distinct Cust_Id,Cust_Name From Temp_Customer
>Where Not Exists
>(Select Cust_Id,Cust_Name From MyDb.dbo.Customer
>Where MyDb.dbo.Customer .Cust_Id = Temp_Customer.Cust_Id)
>Please Help ..
Hi Travis,
SQL Server doesn't have a boolean datatype, so it's not possible to
store the result of a logical expression in a variable. Of course, you
can use any variable to denote true and false in any way that appears to
be logical to you. Popular encodings for true and false are:
- datatype CHAR(1); values 'T'/'F' (or 'Y'/'N' - or even localised
versions [in the Netherlands, we'd use 'J'/'N' for yes/no]).
- datatype tinyint (or bit); values 0 / 1 (where you have to define [AND
DOCUMENT!!!] whether 1 means true and 0 means false or the other way
around).
To return the result of an exists expression, you can either use an IF
statement with two SET statements, or use one SET statement with a CASE
expression.
Example 1, using IF:
DECLARE @.YesOrNo CHAR(1)
IF EXISTS (SELECT *
FROM ...
WHERE ...)
BEGIN
SET @.YesOrNo = 'Y'
END
ELSE
BEGIN
SET @.YesOrNo = 'N'
END
Example 2, using CASE:
DECLARE @.YesOrNo CHAR(1)
SET @.YesOrNo =
CASE
WHEN EXISTS (SELECT *
FROM ...
WHERE ...)
THEN 'Y'
ELSE 'N'
END
Best, Hugo
(Remove _NO_ and _SPAM_ to get my e-mail address)

No comments:

Post a Comment