1

我正在使用 SQL Server 2008。我有以下查询。我喜欢做的是,如果有记录存在,我喜欢将实际日期分配给“N/A”,否则我希望它是手头的 CreatedBy 日期。

   select ActualDate = (CASE
                         WHEN EXISTS
                         (select NeedHand from Truck 
                           where Truck.NeedHand = 0 and Truck.ID = '34343')
                         THEN
                          'N/A'
                         ELSE
                          SELECT  CreatedByDate from Hand  where ID = '34343'
                         END )

我收到以下消息:关键字“select”附近的语法不正确。

4

3 回答 3

3

我认为你的 EXIST 应该是 EXISTS。

于 2012-08-07T15:57:34.187 回答
0

您的查询存在许多问题。下面的版本应该照顾所有这些:

select  ActualDate = 
CASE 
     WHEN EXISTS(
            select NeedHand from Truck 
            where Truck.NeedHand = 0 and Truck.ID = '34343'
            )
     THEN
               'N/A'
     ELSE
               (SELECT  CreatedByDate from Hand  where ID = '34343')
END

我不得不 :

  1. 更改EXISTEXISTS
  2. 更改END CASEEND
  3. 在最后一个查询周围添加括号。
于 2012-08-07T16:00:51.467 回答
0

选项1

SELECT
(
    CASE
        WHEN 
                Exists(SELECT top 1 NeedHand FROM Truck 
                WHERE Truck.NeedHand = 0 and Truck.ID = '34343')
        THEN
                'N/A'
        ELSE
                (SELECT TOP 1 CreatedByDate FROM Hand WHERE ID = '34343')
    END 
)

选项 #2

SELECT
(
    CASE
        WHEN 
                ((SELECT top 1 NeedHand FROM Truck 
                WHERE Truck.NeedHand = 0 and Truck.ID = '34343') IS NOT NULL)
        THEN
                'N/A'
        ELSE
                (SELECT TOP 1 CreatedByDate FROM Hand WHERE ID = '34343')
    END 
)

添加Top 1以避免以下问题

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

于 2012-08-07T16:02:52.217 回答