【问题标题】:what does a select statement returns if condition doesn't match?如果条件不匹配,select 语句会返回什么?
【发布时间】:2012-10-28 12:12:59
【问题描述】:

例如,如果我有以下陈述:

declare @uid int;
set @uid = (select id from tablename where condition)

在这种情况下,如果 select 没有返回结果,@uid 的值会是多少?

【问题讨论】:

  • 尝试自己可能比询问和等待答案更快..
  • 你可以更容易地写这个:select @uid = id from tablename where condition ...
  • 这个问题虽然简单,但在 StackOverflow 中直接明确答案很有用。

标签: sql sql-server select


【解决方案1】:

进行检查,如下所示:

declare @uid int;
set @uid = (select id from tablename where condition)
If @uid IS NULL
  print 'uid is null or not exist'

或者,你可以设置默认值,以防它返回null

 If @uid IS NULL
      set @uid = 0

【讨论】:

    【解决方案2】:

    简单来说就是null

    我已经制作了简单的临时表来测试这个

    declare @temp table 
     (
       id int identity(1,1) not null  ,
       alpha nvarchar(50)
     )
    
     insert into @temp select 'z'
    

    声明了一个变量nvarchar type 并在这个不满足条件的地方获取值然后有null,如果你通过print语句看到那么应该什么都不会打印

    declare @test nvarchar(50)
    
    
     select @test=alpha from @temp where id=70
    
     insert into @temp  select @test 
     select * from @temp
    
    
     print @test
    

    我只是再次插入这个来确认有空

    【讨论】:

      【解决方案3】:

      在这种情况下它会返回 NULL

      【讨论】:

      • 那么整型变量@uid可以保持这个null吗?
      • 是的,它也会为空。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-07-08
      • 1970-01-01
      • 2011-02-16
      • 2021-10-18
      • 1970-01-01
      • 2013-06-28
      • 2021-11-22
      相关资源
      最近更新 更多