使用IF SELECT INTO语句在命令附近发生错误的语法

时间:2013-07-09 21:33:40

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

所以我将在下面发布我的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 

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

1 个答案:

答案 0 :(得分: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;