1

所以我将在下面发布我的 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 个小时,我就是找不到问题。

4

1 回答 1

3

问题是子查询需要 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;
于 2013-07-09T21:35:21.217 回答