小技巧收集(8)-sql变量set赋值

 

/* 很简单的一个例子:
假设有表a 字段id(int) num(int)
定义一个变量 初始化为10
*/
declare   @itemid   as   integer
set   @itemid = 10
-- 这里id=100是不存在的
select   @itemid = 30 * total  from  a  where  id = 100
-- 这里返回值是我初始化的10
select   @itemid

-- 接下来我们把初始化注释注掉
declare   @itemid   as   integer
-- set @itemid=10
--
这里id=100是不存在的
select   @itemid = 30 * total  from  a  where  id = 100
-- 这里返回值是null
select   @itemid
 

结论:也就是说给变量赋值为任何值,只要在计算过程中赋值出现问题 都会返回为原来最近的一次set的值

你可能感兴趣的:(sql)