IF EXISTS(SELECT 1 FROM tb WHERE ID = 3) SELECT [NAME] FROM tb WHERE ID = 3 ELSE SELECT [NAME] = 0
use test go if object_id('test.dbo.tb') is not null drop table tb -- 创建数据表 create table tb ( ID int, NAME char(4) ) go --插入测试数据 insert into tb select 1,'TOM' union all select 2,'JAN' go --代码实现select NAME = case (select count(*) from tb where ID = 3) when 1 then (select NAME from tb where ID = 3) else '' end/*测试结果NAME --------------------- (1 行受影响) */select NAME = case (select count(*) from tb where ID = 2) when 1 then (select NAME from tb where ID = 2) else '' end/*测试结果NAME --------------------- JAN(1 行受影响) */
SELECT [NAME] FROM tb WHERE ID = 3
ELSE
SELECT [NAME] = 0
go
if object_id('test.dbo.tb') is not null drop table tb
-- 创建数据表
create table tb
(
ID int,
NAME char(4)
)
go
--插入测试数据
insert into tb select 1,'TOM'
union all select 2,'JAN'
go
--代码实现select NAME = case (select count(*) from tb where ID = 3) when 1
then (select NAME from tb where ID = 3) else '' end/*测试结果NAME
---------------------
(1 行受影响)
*/select NAME = case (select count(*) from tb where ID = 2) when 1
then (select NAME from tb where ID = 2) else '' end/*测试结果NAME
---------------------
JAN(1 行受影响)
*/