【问题标题】:What is better to use Exists or Select to set this value to bit variable?使用 Exists 或 Select 将此值设置为位变量哪个更好?
【发布时间】:2014-11-28 09:51:22
【问题描述】:

我有指示行是否存在的位(或整数)变量。

是的,我知道最好只检查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)

【问题讨论】:

  • 在第二个例子中,你在哪里设置变量的值?您只是为其设置 1 或 0。
  • 因为BIT只有2个可能的值
  • 我以为您想要变量中的 AccountOperations_ID 的值。检查你在做什么是不正确的。但是,如果您只是希望您的变量成为一个标志,那么您应该考虑将其默认为 0,然后将 IF EXISTS 子句设置为 1。这将是最好的方法。

标签: sql select exists


【解决方案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)

你根本不需要顶部,它可能会给查询带来额外的工作。

【讨论】:

    【解决方案2】:

    添加到评论中:

    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。

    【讨论】:

      【解决方案3】:

      使用IF EXISTS 可以做到这一点,如果行存在则返回true,否则返回false。

          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
      

      【讨论】:

        猜你喜欢
        • 2023-01-27
        • 2021-04-03
        • 2011-08-28
        • 2017-03-04
        • 2010-09-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多