SQL Server的非聚集索引中会存储NULL吗?

原文: SQL Server的非聚集索引中会存储NULL吗?

SQL Server的非聚集索引中会存储NULL吗?

这是个很有意思的问题,下面通过如下的代码,来说明,到底会不会存储NULL。



   
   
  1. --1.建表
  2. if OBJECT_ID('t1') is not null
  3. drop table t1
  4. go
  5. create table t1
  6. (
  7. id int primary key,
  8. v varchar( 20)
  9. )
  10. insert into t1
  11. select 1 , 'aa' union all
  12. select 2 , 'bb' union all
  13. select 3 , 'cc' union all
  14. select 4 , 'dd' union all
  15. select 5 , 'ee' union all
  16. select 6 , 'ff' union all
  17. select 7 , null union all
  18. select 8 , 'gg' union all
  19. select 9 , null
  20. go
  21. --2.创建一个非聚集索引
  22. create index idx_t1_v on t1(v)
  23. go
  24. --3.index_id = 2 为idx_t1_v索引
  25. select *
  26. from sys.indexes
  27. where object_id = object_id( 't1')
  28. --hobt_id = 72057594041466880
  29. select *
  30. from sys.partitions
  31. where index_id = 2
  32. and object_id = object_id( 't1')
  33. --root_page = 0xAF0000000100
  34. select *
  35. from sys.system_internals_allocation_units
  36. where container_id = 72057594041466880
  37. --4.0100:文件id,而AF是16进制,转化为10进制是 175,pageId = 175
  38. DBCC page( 12, --数据库id : 10
  39. 1, --文件id: 1
  40. 175, --页id: 188
  41. 3) --with tableresults
  42. /*
  43. 文件id 页id 索引行号 层级 v列的值 这个v列值所对应的行号 id列的hash值
  44. FileId PageId Row Level v (key) id (key) KeyHashValue
  45. 1 175 0 0 NULL 7 (8d4dc9cd25b3)
  46. 1 175 1 0 NULL 9 (fd07a7dffc59)
  47. 1 175 2 0 aa 1 (e5e354933dff)
  48. 1 175 3 0 bb 2 (df47e5a393e1)
  49. 1 175 4 0 cc 3 (36248ab30914)
  50. 1 175 5 0 dd 4 (40ee14f42575)
  51. 1 175 6 0 ee 5 (a98d7be4bf80)
  52. 1 175 7 0 ff 6 (9329cad4119e)
  53. 1 175 8 0 gg 8 (f34ca041b78d)
  54. */
  55. --5.走的索引查找
  56. select *
  57. from t1
  58. where v is null
  59. --走的是索引扫描,之所以这里走索引,是因为在v列的非聚集索引中,也包含了所有的数据
  60. select *
  61. from t1
  62. where v like '%a%'

从第4个输出,可以看出非聚集索引中是存储了NULL的。


发布了416 篇原创文章 · 获赞 135 · 访问量 94万+

猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/12019991.html
今日推荐