---
title: "select查询 赋值"
author: "ch.net"
date: "2008-12-08T16:45:06Z"
tags: []
slug: "select"
draft: false
lastmod: "2008-12-08T16:45:21Z"
id: 288906
url: "https://haha-net.iteye.com/blog/288906"
---

用 set 可以直接将 null 赋值给某变量　　如： set @Id = null

  

 

用 select 查询时赋值，需注意几个问题

 

1.   当查询语句 没有用到聚合函数，若查询结果为空，则不会给变量赋值 如：    

 

      select @Id = Id  from tab where Id = -1

      @Id 为 null

 

2.  当查询语句 用到聚合函数 ( AVG  MIX  MAX SUM )，查询结果 不管　是不是空，都会给变量赋值　如：

    

      set @Id = 0

      select @Id =  avg( Id )  from tab where Id = -1 

      若该查询结果为空，则 @Id 为 null　

 

3.  当查询语句  用到聚会函数　Count，若查询结果为空，则会给变量赋0　如：

    

     select @Id =  count( Id )  from tab where Id = -1 

     @Id 为 0