sql-server - 寻找编写代码逻辑的更好方法
问题描述
我有以下带有CASE
语句的代码:
--to check if any record with this conditon present in table
--then pick col1, if such record exists
CASE WHEN EXISTS (SELECT col1 from table where col2=1 and col3 is not null)
THEN (SELECT col1 from table where col2=1 and col3 is not null)
ELSE
<something else>
END
那里的条件更多,代码看起来很大。WHEN
也可以看到重复THEN
。
重写代码的更好方法。对性能没有影响
解决方案
我不确定您列出的查询将如何工作,它是更大查询的一部分吗?SET 语句的一部分?我认为您正在寻找的可能是将 SELECT 拉到您的 CASE 之外,就像这样
;with cteSampleData as (
SELECT * FROM (VALUES ('Row 1', 1, NULL)
,('Row 2', 1, 'Also row 2')
,('Row 3', 2, NULL)
,('Row 4', 2, 'Also row 4')
,('Row 5', 1, 'Also row 5')
) as SampleData(Col1, Col2, Col3)
)SELECT SD.Col1, SD.Col2, SD.Col3,
CASE WHEN col2=1 and col3 is not null
THEN col1
ELSE
CONCAT('Anything other than ', Col1)
END as MyCase
FROM cteSampleData as SD
请注意,在您编写的查询中,您可能会在 THEN 子句中返回多行,我认为无论设置如何,这都是一个错误,但至少在默认 SQL Server 配置中是一个错误。
推荐阅读
- javascript - Javascript如何为sim树创建动态变量名
- javascript - 我想在“javascript”中创建一个链接列表
- c# - MediatR 发布和 MediatR 发送
- c++ - 如何创建对任何实现方括号运算符的类的引用?
- javascript - 如何为胜利轴上的刻度动态创建 y 轴值?
- c++ - `&ClassName::function` 的调用方法代表什么?
- html - 如何将materialboxed与materialize carousell结合起来?
- r - 删除不良数据的“带”
- c - 这个按位运算有什么作用?
- database - 如何在数据库 b 树上执行带有组合子句的 SQL 操作