【问题标题】:Incorrect Syntax near Order with IF SELECT INTO Statement带有 IF SELECT INTO 语句的 Order 附近的语法不正确
【发布时间】:2013-07-07 16:13:09
【问题描述】:

所以我将在下面发布我的 SQL 代码(实际上只是失败的部分),这也适用于 SQL Server:

SELECT @newPID = (SELECT policy_id FROM #StatusTable);
SELECT @newTXN = (SELECT txn_number FROM #StatusTable);

IF (@newPID IS NOT NULL) 
BEGIN
    SELECT * 
    INTO #StatusTable 
        (SELECT TOP (1) 
             id, policy_product_id, txn_number, agent_id, user_id, old_status_id, 
             new_status_id, status_update_date, status_type_id, notes, policy_id
         FROM  sales_blotter_status_changes
         WHERE (policy_id = @newPID)
         ORDER BY status_update_date DESC)
END 
ELSE BEGIN
    SELECT * 
    INTO #StatusTable 
        (SELECT TOP (1) 
             id, policy_product_id, txn_number, agent_id, user_id, old_status_id, 
             new_status_id, status_update_date, status_type_id, notes, policy_id
         FROM  sales_blotter_status_changes
         WHERE (txn_number = @newTXN)
         ORDER BY status_update_date DESC)
END 

因此,如果您基本上看一下我正在尝试根据前一个表中的特定字段是否为 Null 来创建临时表的内容。当我运行这个查询时,我得到一个不正确的语法错误,指出问题在 ORDER 旁边(即使它没有说明我很确定它会是第一个)。有人可以看看这个,让我知道我哪里出错了,我已经为此工作了大约 4 个小时,我就是找不到问题。

【问题讨论】:

    标签: sql-server tsql select sql-order-by


    【解决方案1】:

    问题是子查询在 sql-server 中需要一个别名。所以,试试这个快速修复:

    SELECT @newPID = (SELECT policy_id FROM #StatusTable);
    SELECT @newTXN = (SELECT txn_number FROM #StatusTable);
    
    IF (@newPID IS NOT NULL) 
    BEGIN
    SELECT * INTO #StatusTable (SELECT TOP (1) id, policy_product_id, txn_number, agent_id, user_id, old_status_id, new_status_id, status_update_date, status_type_id, notes, policy_id
    FROM  sales_blotter_status_changes
    WHERE (policy_id = @newPID)
    ORDER BY status_update_date DESC) t
    END ELSE BEGIN
    SELECT * INTO #StatusTable (SELECT TOP (1) id, policy_product_id, txn_number, agent_id, user_id, old_status_id, new_status_id, status_update_date, status_type_id, notes, policy_id
    FROM  sales_blotter_status_changes
    WHERE (txn_number = @newTXN)
    ORDER BY status_update_date DESC) t
    END 
    

    顺便说一句,您不需要子查询。事实上,您甚至不需要两个查询。您可以将逻辑编写为:

    SELECT TOP (1) id, policy_product_id, txn_number, agent_id, user_id, old_status_id, new_status_id, status_update_date, status_type_id, notes, policy_id
    INTO #StatusTable 
    FROM  sales_blotter_status_changes
    WHERE (@newPID is not null and policy_id = @newPID) or (@newPID is null and txn_number = @newTXN)
    ORDER BY status_update_date DESC;
    

    【讨论】:

    • 谢谢 Gordon,这就是问题所在,更简化的第二个解决方案更好。
    猜你喜欢
    • 1970-01-01
    • 2013-12-16
    • 2018-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-11
    相关资源
    最近更新 更多