SQL Server: If Exists ; Else

SQL Server IF EXISTS THEN 1 ELSE 2

If you want to do it this way then this is the syntax you're after;

IF EXISTS (SELECT * FROM tblGLUserAccess WHERE GLUserName ='xxxxxxxx') 
BEGIN
SELECT 1
END
ELSE
BEGIN
SELECT 2
END

You don't strictly need the BEGIN..END statements but it's probably best to get into that habit from the beginning.

SQL Server: IF EXISTS ; ELSE

EDIT

I want to add the reason that your IF statement seems to not work. When you do an EXISTS on an aggregate, it's always going to be true. It returns a value even if the ID doesn't exist. Sure, it's NULL, but its returning it. Instead, do this:

if exists(select 1 from table where id = 4)

and you'll get to the ELSE portion of your IF statement.


Now, here's a better, set-based solution:

update b
set code = isnull(a.value, 123)
from #b b
left join (select id, max(value) from #a group by id) a
on b.id = a.id
where
b.id = yourid

This has the benefit of being able to run on the entire table rather than individual ids.

SQL Server - How to create IF EXISTS...SELECT AND SELECT

Your parentheses are off; you need two EXISTS conditions:

IF EXISTS (SELECT Id FROM Library.Book WHERE Title = @BookTitle
) AND
EXISTS (SELECT Id FROM Library.Genre WHERE Name = @GenreName
)
BEGIN
. . .
END

If exists else if condition in SQL Server

You have an extra (unnecessary) closing parenthesis at the end of your second SELECT statement. Remove it and the error should go away:

select @obgCode = o.icd10code,@content = o.trimester,@history = t.history from   ICD10Master.dbo.icd10obginfectiousCrosswalk i
inner join Icd10TempDisease t on i.icdcode = t.Code1 and t.Status in(0,1,5)
inner join ICD10Master.dbo.obgcomplications o on i.obgcode=o.code
where o.trimstatus =@condition2

SQL Server returning a value and checking if exists on the same select (one select operation)

--You could change your IF Exists to just a select Active where employeeId = Id , 
--if it is NULL they don't exist, else select the active value.

DECLARE @isActive BIT

--Instead of IF EXISTS, just set the BIT value to whatever is returned,
--If NULL they don't exist
SET @isActive = SELECT TOP 1 [FlagActive] FROM Employees WHERE Id = @IdEmployee

IF @isActive IS NOT NULL
BEGIN

IF @IsActive = 1
BEGIN
-- Employee is active: Do some stuff
END
ELSE
BEGIN
-- Employee is inactive: Do some stuff
END
END


Related Topics



Leave a reply



Submit