如果列文本为空或为空时如何更改列文本?
我的查询:
Select TOP 1 ISNULL(NULLIF(DR.Name,''),'Not Exists') as Name,
DR.Name as Name ,Coalesce(NullIf(rtrim(DR.Name),''),'Not Exist') as Name,
Name = case when DR.Name is null then 'Not Exists'
when DR.Name='' then 'Not Exists' else DR.Name end
from Transfer TR
join Driver DR on DR.OID=TR.DriverID
WHERE TR.TruckID=51 AND TR.Statues<>7 and TR.DateScheduled<GETDATE()
AND TR.DateScheduled>=DATEADD(DAY,-7,GETDATE()) ORDER BY TR.OID DESC
结果:
答案 0 :(得分:1)
如果您只需要一个列,那么您可以使用子选择,这样当查询不返回任何行时,您仍会获得not exists
:
SELECT Name = ISNULL(( SELECT TOP 1 NULLIF(DR.Name,'')
FROM Transfer AS TR
INNER JOIN Driver AS DR
ON DR.OID = TR.DriverID
WHERE TR.TruckID = 51
AND TR.Statues <> 7
AND TR.DateScheduled < GETDATE()
AND TR.DateScheduled >= DATEADD(DAY, -7, GETDATE())
ORDER BY TR.OID DESC), 'Not Exists');
如果您需要多列,那么您可以将Not Exists
记录合并到查询的底部,将所有这些记录放在子查询中,然后再次选择前1,确保您的实际值优先(通过添加列SortOrder
):
SELECT TOP 1 Name, SomeOtherColumn
FROM ( SELECT TOP 1
Name = NULLIF(DR.Name,''),
SomeOtherColumn,
SortOrder = 0
FROM Transfer AS TR
INNER JOIN Driver AS DR
ON DR.OID = TR.DriverID
WHERE TR.TruckID = 51
AND TR.Statues <> 7
AND TR.DateScheduled < GETDATE()
AND TR.DateScheduled >= DATEADD(DAY, -7, GETDATE())
ORDER BY TR.OID DESC
UNION ALL
SELECT 'Not Exists', NULL, 1
) AS t
ORDER BY SortOrder;
答案 1 :(得分:0)
我不完全确定我理解你的问题,但是如果你想“一气呵成地”捕捉空值和空字符串,请试试这个:
select TOP 1
case when length(trim(coalesce(DR.Name, ''))) = 0 then
'Not Exists'
else
DR.Name
as Name
....
coalesce
捕获NULL
并设置替换值。 trim
删除任何填充,length
检查剩下的是否为空字符串 - &gt;所以这涵盖了空值,填充和非填充的平凡字符串。
答案 2 :(得分:0)
假设该值具有常规空格,以下将保留您的方法:
Select TOP 1 ISNULL(NULLIF(ltrim(rtrim((DR.Name))), ''), 'Not Exists') as Name,
我可能更明确地说:
select top 1 (case when ltrim(rtrim((DR.Name)) = '' or DR.Name is null then 'Not Exists'
else DR.Name end) as Name
除非您还希望在输出中从Name
中删除空格。
如果您有其他字符,则可以使用ASCII()
来查找它们。类似的东西:
select ASCII(LEFT(DR.Name, 1))
. . .
where LEFT(DR.Name, 1) NOT LIKE '[a-zA-Z0-9 ]' -- you can expand this list of allowed characters
答案 3 :(得分:0)
在我看来,您实际上并没有找到一种方法来替换空字符串,而不是存在&#39;而是一个空的结果集。
换句话说:看起来您正在寻找一种展示“不存在”的方法。如果您的查询没有返回任何行。如果这是你正在寻找的,那么首先&#34;添加&#34; a&#39;不存在&#39;记录到您的结果集,然后显示最佳行,即在存在这样的行的情况下所需的行,否则您的“不存在”#39;行。
select top 1 name
from
(
select name, tr.oid
from transfer tr
join driver dr on dr.oid=tr.driverid
where tr.truckid=51 and tr.statues<>7 and tr.datescheduled<getdate()
and tr.datescheduled>=dateadd(day,-7,getdate())
union all
select 'Not Exists', -1
)
order by oid desc;
我为虚拟OID选择了-1。它必须是小于任何真实OID的值。因此,如果您有负值,请将该值设置得更小。