关于T-SQL公共表达式()的问题

查询了一些相关资料,公共表达式之后直接接SQL语句(insert,update,select等)

那么如果后面要写一些逻辑判断该怎样写呢?

例如:
WITH Emps AS
(
SELECT empid, mgrid, firstname, lastname
FROM HR.Employees
WHERE empid = 5

UNION ALL

SELECT Emp.empid, Emp.mgrid, Emp.firstname, Emp.lastname
FROM Emps AS Mgr
JOIN HR.Employees AS Emp
ON Emp.mgrid = Mgr.empid
)

如果查询出Emps 是空的,错误处理(insert into T1 values('1','2',null,null))
如果Emps不是空的,将Emps结果插入到T1中(insert into T1 select * from emps)

谢谢了~!

sql

2个回答

WITH Emps AS
(
SELECT empid, mgrid, firstname, lastname
FROM HR.Employees
WHERE empid = 5

UNION ALL

SELECT Emp.empid, Emp.mgrid, Emp.firstname, Emp.lastname
FROM Emps AS Mgr
JOIN HR.Employees AS Emp
ON Emp.mgrid = Mgr.empid
)
select * into #aa from Emps

if exists (select * from #aa ) insert into T1 select * from #aa
if not exists (select * from #aa ) insert into T1 values('1','2',null,null)

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问