让CTE像:
WITH fnl as
(select lo.id , s.service_name , lo.obj_name ,
........
from dbo.r_objects ro
inner join dbo.services s on ro.service_id = s.id
inner join dbo.local_objects lo on ro.local_object_id = lo.id
where ro.service_id = @service_id
)
select id , service_name , CAST(obj_name as varbinary(200)) obj_name
FROM fnl
WHERE ....... some logic
它的工作很好。现在我想检查 fnl 中的数据是否为空,然后写'数据为空' 我试着这样:
WITH fnl as
(select lo.id , s.service_name , lo.obj_name ,
........
from dbo.r_objects ro
inner join dbo.services s on ro.service_id = s.id
inner join dbo.local_objects lo on ro.local_object_id = lo.id
where ro.service_id = @service_id
)
select @table_count = COUNT(*) from fnl
IF @table_count > 0
begin
select id , service_name , CAST(obj_name as varbinary(200)) obj_name
FROM fnl
WHERE ....... some logic
end
else
set @check = 'Data is empty'
...............some logic here
当我的exec程序有错误时:无效的对象名称'fnl'如何检查空?我尝试IF EXISTS
但也有错误
编辑:
* 我解决它,创建#tbl然后将fnl中的所有数据插入#tbl,因为在CTE fnl中你只能使用一次,我使用它两次并出错。然后检查是否存在这样的数据: * IF EXISTS (select top 1 1 from #tbl)
如果存在数据则从#tbl中选择数据否则使用某些逻辑
答案 0 :(得分:3)
select lo.id , s.service_name , lo.obj_name ,
........
INTO #temp
from dbo.r_objects ro
inner join dbo.services s on ro.service_id = s.id
inner join dbo.local_objects lo on ro.local_object_id = lo.id
where ro.service_id = @service_id
IF EXISTS (SELECT 1 FROM #temp)
begin
select id , service_name , CAST(obj_name as varbinary(200)) obj_name
FROM #temp
WHERE ....... some logic
end
else
begin
set @check = 'Data is empty'
...............some logic here
end
答案 1 :(得分:1)
公用表表达式仅存在于下一个SQL语句中。考虑调整您的方法 - 为什么在此阶段检查数据是否为空?在应用程序方面可以更好地处理这种检查。
或者,如果你肯定想在数据库中这样做,可以选择以下方法:
答案 2 :(得分:0)
我认为CTE不适合您的查询。做这样的事情我会好得多。而不是你的CTE只是将你所拥有的内容放在那个子选择中。稍后您可以继续检查您的可维护性。
DECLARE @table_count INT
SELECT @table_count = COUNT(*)
FROM ( SELECT somestuff
FROM SOMEtables ) a