首页 > 解决方案 > 寻找编写代码逻辑的更好方法

问题描述

我有以下带有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

重写代码的更好方法。对性能没有影响

标签: sql-servertsqlcase

解决方案


我不确定您列出的查询将如何工作,它是更大查询的一部分吗?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 配置中是一个错误。


推荐阅读