zoukankan      html  css  js  c++  java
  • SqlServer中使用Select语句给变量赋值的时候需要注意的一个问题

    我们知道在SqlServer中可以用Select语句给变量赋值,比如如下语句就为int类型的变量@id赋值

     1 declare @id int=-1;
     2 
     3 select @id=id from 
     4 (
     5 select 1 as id
     6 union all 
     7 select 2 as id
     8 union all 
     9 select 3 as id
    10 ) as t
    11 
    12 select @id

    执行上面的代码会显示下面的查询结果,结果显示最后@id的值为3,那么意味着上面第3行的select语句每返回一行数据记录,sqlserver就用id列为@id进行了一次赋值,而最后一行数据记录id列为3,所以在第12行的查询中最后查得@id为3

    那么如果上面第3行的查询语句一行结果都没有返回,那么最终在12行的查询中@id会是什么值呢?很多人可能会想到@id会为null。

    接下来我们将上面的代码稍作更改如下,我们在第3行的查询中加入了where条件1<>1,这个条件是永远都不会被满足的始终为false,所以现在第3行的select语句一条记录都不会返回

     1 declare @id int=-1;
     2 
     3 select @id=id from 
     4 (
     5 select 1 as id
     6 union all 
     7 select 2 as id
     8 union all 
     9 select 3 as id
    10 ) as t
    11 where 1<>1
    12 
    13 select @id

    我们查看一下现在代码的执行结果,我们发现结果并不为null而是-1,相当于第3行的select语句根被就没有为@id赋值,原因也很简单,因为前面我们说了第3行的select语句返回多少条记录,就会为@id赋多少次值,现在它一行记录都没有返回,那么就不会为@id赋值,所以最终@id还是为初始值-1

    现在我们再将代码改为如下所示,将查询结果sum后的聚合值赋值给变量@id

     1 declare @id int=-1;
     2 
     3 select @id=sum(id) from 
     4 (
     5 select 1 as id
     6 union all 
     7 select 2 as id
     8 union all 
     9 select 3 as id
    10 ) as t
    11 where 1<>1
    12 
    13 select @id

    这一次的结果显示@id为null了,原因也很简单因为第3行的查询最后只返回了一行为null记录,所以对@id进行了一次赋值,所以最后在13行的查询中@id显示为null

    所以在使用Select语句为sql变量赋值的时候,一定要清楚变量的值是取决于select语句的查询结果,如果select语句最后一行数据都没返回,那么select语句就不会为变量赋值。如果select语句最后返回了多行记录,那么变量就为最后一行记录的值。

  • 相关阅读:
    LeetCode 1245. Tree Diameter
    LeetCode 1152. Analyze User Website Visit Pattern
    LeetCode 1223. Dice Roll Simulation
    LeetCode 912. Sort an Array
    LeetCode 993. Cousins in Binary Tree
    LeetCode 1047. Remove All Adjacent Duplicates In String
    LeetCode 390. Elimination Game
    LeetCode 1209. Remove All Adjacent Duplicates in String II
    LeetCode 797. All Paths From Source to Target
    LeetCode 1029. Two City Scheduling
  • 原文地址:https://www.cnblogs.com/OpenCoder/p/5785108.html
Copyright © 2011-2022 走看看