什么更好使用Exists或Select将此值设置为位变量?

时间:2014-11-28 09:51:23

标签: sql select exists

我有一个bit(或int)变量,表示行是否存在。

是的,我知道最好只检查EXISTS,但目前我需要将其设置为我的变量。

所以问题:使用SELECTEXISTS

更好
DECLARE @signoff int    
set @signoff = 0


Set @signoff = (SELECT TOP 1
    AccountsOperations_ID
    FROM AccountsOperations
    WHERE Operation_ID = 3 and Submission_ID = @SubmissionID and AccountDate is null)

然后检查

if @signoff is null or @signoff = 0

DECLARE @signoff bit
    set @signoff = 0

Set @signoff = SELECT CAST(
   CASE WHEN EXISTS(SELECT TOP 1
             AccountsOperations_ID
             FROM AccountsOperations
             WHERE Operation_ID = 3 and Submission_ID = @SubmissionID and AccountDate is null) 
       THEN 1 
   ELSE 
        0 
   END 
AS BIT)

3 个答案:

答案 0 :(得分:1)

对我来说,就是这样:

DECLARE @signoff bit
    set @signoff = 0

Set @signoff = SELECT CAST(
   CASE WHEN EXISTS(SELECT 1
             FROM AccountsOperations
             WHERE Operation_ID = 3 and Submission_ID = @SubmissionID and AccountDate is null) 
       THEN 1 
   ELSE 
        0 
   END 
AS BIT)

您根本不需要顶部,这可能会导致查询的额外工作。

答案 1 :(得分:1)

添加评论:

DECLARE @signoff bit
    set @signoff = 0

IF EXISTS(SELECT 1
             FROM AccountsOperations
             WHERE Operation_ID = 3 and Submission_ID = @SubmissionID and AccountDate is null) 

SELECT @signoff = 1

您不需要TOPELSE,因为您无论如何都要将其默认为0.

答案 2 :(得分:0)

使用IF EXISTS你可以这样做,如果row存在,则返回true。

    DECLARE @signoff bit


    IF EXISTS
    (
    SELECT 1
           AccountsOperations_ID
    FROM   AccountsOperations
    WHERE  Operation_ID = 3 and Submission_ID = @SubmissionID and AccountDate is null
    ) 
    SET signoff = 1 -- row exists
    ELSE
    SET signoff = 0 -- row doesn't exists