34,590
社区成员
发帖
与我相关
我的任务
分享
DECLARE @t TABLE(id INT)
INSERT @t SELECT 55
DECLARE @i INT
SELECT @i= id FROM @t WHERE id=55
SELECT @i
--55
SELECT @i= id FROM @t WHERE id=99
SELECT @i
--55
SET @i=(SELECT id FROM @t WHERE id=99)
SELECT @i
--NULL
SELECT @i= (SELECT id FROM @t WHERE id=99)
SELECT @i
--NULL
--看如下例子可以很容易理解这个问题:
create table test (id int,num int)
insert into test select 1,10
insert into test select 2,20
declare @i int
--存在num=10的数据
select @i = id from test where num=10
select @i
--where条件不满足,但赋值后@i仍旧为1,这是不对的,应该为null
select @i = id from test where num=111
select @i
--以下语句得到的结果是对的,为null
set @i = (select id from test where num=111)
select @i
drop table test
/*
--返回:
1
1
null
*/
--看如下例子可以很容易理解这个问题:
create table test (id int,num int)
insert into test select 1,10
insert into test select 2,20
declare @i int
--存在部门编码='1'的数据
select @i = id from test where num=10
select @i
--where条件永假,但赋值后@i仍旧为1,这是不对的,应该为null
select @i = id from test where num=111
select @i
--以下语句得到的结果是对的,为null
set @i = (select id from test where num=111)
select @i
drop table test
/*
--返回:
1
1
null
*/
USE AdventureWorks;
GO
DECLARE @rows int;
SET @rows = (SELECT COUNT(*) FROM Sales.Customer);
SELECT @rows;
declare @i int
--存在部门编码='1'的数据
select @i = 级别 from 部门 where 部门编码='1'
select @i
--where条件永假,但赋值后@i仍旧为1,这是不对的,应该为null
select @i = 级别 from 部门 where 1=2
select @i
--以下语句得到的结果是对的,为null
set @i = (select 级别 from 部门 where 1=2)
select @i
/*
--返回:
1
1
null
*/
对变量的赋值,不建议用select,建议用set
--这样也是对的
set @var = (select count(*) from tb)
declare @i int
--存在部门编码='1'的数据
select @i = 级别 from 部门 where 部门编码='1'
select @i
--where条件永假,但赋值后@i仍旧为1,这是不对的,应该为null
select @i = 级别 from 部门 where 1=2
select @i
--以下语句得到的结果是对的,为null
set @i = (select 级别 from 部门 where 1=2)
select @i