SELECT Column1
FROM Table1
WHERE PKColumn = SomeValue
我只选择一个列,我的查询肯定会返回0或1行。如果没有返回行,我想选择一些默认值,如Some Default
,否则返回值。
我试过像
这样的东西SELECT CASE WHEN COUNT(1) = 1 THEN Column1 ELSE 'Some Default' END AS Column1
FROM Table1
WHERE PKColumn = SomeValue
GROUP BY Column1
但它没有用。
有没有办法在单个SQL语句中执行此操作?
答案 0 :(得分:1)
我认为你可以使用这样的查询:
SELECT TOP(1)
CASE WHEN EXISTS(SELECT 1 FROM t WHERE PKColumn = SomeValue) THEN Column1
ELSE 'Some Default' END AS Column1
FROM t;
或EXISTS
使用UNION
:
SELECT 'Some Default' As Column1
WHERE NOT EXISTS(SELECT 1 FROM t WHERE PKColumn = SomeValue)
UNION ALL
SELECT Column1
FROM t
WHERE PKColumn = SomeValue;
答案 1 :(得分:1)
您可以使用COALESCE
按顺序计算参数并返回当前的值 第一个表达式,最初不会计算为NULL。
SELECT COALESCE((SELECT TOP 1 Column1 FROM Table1 WHERE PK = SomeValue), 'DefaultValue')
或者像这样:
DECLARE @ReturnValue INT = 3 -- Default value
SELECT TOP 1 @ReturnValue = Column1 FROM Table1 WHERE PK = SomeValue
SELECT @ReturnValue
答案 2 :(得分:0)
SELECT
[Column1] = ISNULL([t2].[Column1], 'Some Default')
FROM
[Table1] AS [t1]
OUTER APPLY
(
SELECT
[Column1]
FROM
[Table1]
WHERE
[PKColumn] = [t1].[PKColumn]
) AS [t2]
WHERE
[t1].[PKColumn] = 'SomeValue';
答案 3 :(得分:0)
也许可以尝试使用LEN而不是COUNT来检查Column1是否有值?
SELECT CASE WHEN LEN(Column1) > 0 THEN Column1 ELSE 'Some Default' END AS Column1
FROM Table1
WHERE PKColumn = SomeValue
GROUP BY Column1