T-SQL: if exists always return true?
What do you think , does the Stored Procedure always return 1 ?
I am concerned about the 开发者_JS百科if exists(..)
BEGIN
DECLARE @IsUserExisting bit
SET NOCOUNT ON
IF Exists
(
Select null FROM G_User WHERE
SamAccountName = @SamAccountName
AND NetBIOSDomainName = @NetBIOSDomainName
)
BEGIN
SET @IsUserExisting = 1
END
ELSE
BEGIN
SET @IsUserExisting = 0
END
Select @IsUserExisting
END
No, if the WHERE clause doesn't return anything IF Exists() returns false and consequently @IsUserExisting is set to 0.
Makis already answered your question, but i would like to suggest the following
You could simplify your code with:
declare @IsUserExisting bit;
set @IsUserExisting = (
select count(*) from G_User
where SamAccountName = @SamAccountName and
NetBIOSDomainName = @NetBIOSDomainName);
select @IsUserExisting;
I think the following is even shorter in your case.
select count(*) from G_User
where SamAccountName = @SamAccountName and
NetBIOSDomainName = @NetBIOSDomainName)
BEGIN
DECLARE @IsUserExisting bit
SET NOCOUNT ON
IF Exists
(
Select null FROM G_User WHERE
SamAccountName = @SamAccountName
AND NetBIOSDomainName = @NetBIOSDomainName
)
BEGIN
SET @IsUserExisting = 1
END
ELSE
BEGIN
SET @IsUserExisting = 0
END
Select @IsUserExisting
END
i tried using this but when true it sets @IsUserExisting = -1
!!
You should not use Select Count() if you are only testing to see if something exists. While it should return fairly quickly in this case, If EXISTS() will return true immediately when it finds a matching record. Select Count() will look at all records in order to give you a complete count, thus adding unnecessary overhead.
精彩评论