如何从我的结果中删除 CASE 语句?
Posted
技术标签:
【中文标题】如何从我的结果中删除 CASE 语句?【英文标题】:How to remove CASE statements from my results? 【发布时间】:2021-12-09 06:20:47 【问题描述】:我正在编写一个查询来返回一些信息,但存储过程不会在页面中返回结果,因为这些值与表定义不匹配。我理解这个错误。但我使用 case 语句根据字段进行过滤(无论是否收到 t.TimeCallWasReceived)。当我这样做时,它允许 sp 在用户检查数据库更改或使用 signalR 检测数据库更改时运行。我不希望 CASE 语句成为我结果的一部分。我知道我可以更改页面或临时表,但我想知道我是否可以在 t-sql 中执行任何操作以在所述结果中不包含 case 语句的情况下返回结果。查询如下。
SELECT DISTINCT
c.Num,
'Notified for pickup ' + (CONVERT(varchar(30), c.ServiceCalled, 100)) + '. Number ' + c.Num AS Issue,
RTRIM(c.NameFirst) + ' ' + RTRIM(c.NameLast) AS CusName,
(CASE
WHEN t.TimeCallWasReceived IS NULL THEN CONVERT(varchar(20), t.TimeCallWasReceived, 113)
ELSE 'NO'
END) AS CallReceivedAt
FROM tblCustomer c
LEFT JOIN tblTransportation t ON t.Num = c.Num
WHERE t.TimeCallWasReceived IS NULL
AND c.Type = 'Type1'
AND c.ServiceCalled IS NOT NULL
AND c.TransportNum IS NULL
AND LEFT(c.Num, 2) <> 'CR'
AND LEFT(c.Num, 2) <> 'TR'
AND (c.Status <> 'Void'
OR c.Status <> 'Closed')
AND ((DATEDIFF(MINUTE, c.ServiceCalled, GETDATE())) > 180)
AND c.Type <> 'VOID'
AND c.Type <> 'NON'
AND c.Type <> 'Walk-In'
AND c.Type <> 'CFR'
AND c.CaseType <> 'PAP'
AND c.ServiceCalled >= DATEADD(DAY, -2, GETDATE())
ORDER BY c.Num DESC;
【问题讨论】:
仅供参考,这是一个CASE
表达式,而不是CASE
语句。
IIF (t.TimeCallWasReceived IS NULL, CONVERT(varchar(20), t.TimeCallWasReceived, 113), 'NO') AS CallReceivedAt
我真的不明白你在这里追求什么。如果您不希望结果中出现CASE
表达式定义的列,则将其从SELECT
中删除。为什么你不能这样做?
RE: "...但是存储过程不会在页面中返回结果,因为值与表定义不匹配..." 这句话很令人困惑,您在说什么“页面”和“表格”?就像在此之前有一整段解释/上下文丢失了。
条件是错误的WHEN t.TimeCallWasReceived IS NULL
你不能转换它,在这种情况下应该返回'NO'
。
【参考方案1】:
--1. Since the WHERE clause has `t.TimeCallWasReceived IS NULL`, you will see only ---'NO' in the CallReceivedAt result column.
--2. Since the WHERE clause has `c.Type = 'Type1'`, it makes unnecessary to look for
c.Type <> 'VOID'
c.Type <> 'NON'
c.Type <> 'Walk-In'
c.Type <> 'CFR'
--because they are exclusive for the rest of the values different than 'Type1'.
--3. I don't see a way to get rid of the CASE
-- Perhaps you like this way better:
CASE ISNULL(t.TimeCallWasReceived, '')
WHEN '' THEN CONVERT(varchar(20), t.TimeCallWasReceived, 113)
ELSE 'NO'
END
【讨论】:
又一次打了就跑以上是关于如何从我的结果中删除 CASE 语句?的主要内容,如果未能解决你的问题,请参考以下文章
SQL Server 2012:如何在 @Var 前后使用文字在 Case 语句中显示 @Var 结果